| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| node-npmtest-svg.js/ | 100% | (153 / 153) | 100% | (126 / 126) | 100% | (28 / 28) | 100% | (153 / 153) | |
| node-npmtest-svg.js/node_modules/svg.js/ | 8.33% | (1 / 12) | 100% | (0 / 0) | 0% | (0 / 3) | 8.33% | (1 / 12) | |
| node-npmtest-svg.js/node_modules/svg.js/.config/ | 33.33% | (6 / 18) | 0% | (0 / 2) | 20% | (1 / 5) | 33.33% | (6 / 18) | |
| node-npmtest-svg.js/node_modules/svg.js/bench/ | 6.25% | (2 / 32) | 0% | (0 / 4) | 10% | (1 / 10) | 6.25% | (2 / 32) | |
| node-npmtest-svg.js/node_modules/svg.js/dist/ | 1.3% | (25 / 1922) | 0.74% | (9 / 1221) | 0.6% | (3 / 503) | 1.3% | (24 / 1848) | |
| node-npmtest-svg.js/node_modules/svg.js/spec/lib/jasmine-2.5.2/ | 9.67% | (207 / 2140) | 1.33% | (12 / 901) | 0.72% | (4 / 555) | 9.81% | (207 / 2110) | |
| node-npmtest-svg.js/node_modules/svg.js/spec/spec/ | 0.74% | (49 / 6666) | 1.92% | (1 / 52) | 0% | (0 / 1925) | 0.74% | (49 / 6653) | |
| node-npmtest-svg.js/node_modules/svg.js/src/ | 4.3% | (78 / 1812) | 0% | (0 / 1145) | 0.62% | (3 / 482) | 4.48% | (78 / 1742) |
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| example.js | 100% | (83 / 83) | 100% | (73 / 73) | 100% | (12 / 12) | 100% | (83 / 83) | |
| lib.npmtest_svg.js.js | 100% | (16 / 16) | 100% | (14 / 14) | 100% | (3 / 3) | 100% | (16 / 16) | |
| test.js | 100% | (54 / 54) | 100% | (39 / 39) | 100% | (13 / 13) | 100% | (54 / 54) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 | 2 2 2 2 2 2 2 1 2 2 2 2 1 2 2 2 2 2 1 2 1 1 1 1 1 1 1 1 1 2 1 1 1 1 2 2 3 3 3 3 1 3 3 3 1 3 1 1 1 1 1 1 1 1 1 1 1 1 6 6 1 2 1 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | /*
example.js
quickstart example
instruction
1. save this script as example.js
2. run the shell command:
$ npm install npmtest-svg.js && PORT=8081 node example.js
3. play with the browser-demo on http://127.0.0.1:8081
*/
/* istanbul instrument in package npmtest_svg_js */
/*jslint
bitwise: true,
browser: true,
maxerr: 8,
maxlen: 96,
node: true,
nomen: true,
regexp: true,
stupid: true
*/
(function () {
'use strict';
var local;
// run shared js-env code - pre-init
(function () {
// init local
local = {};
// init modeJs
local.modeJs = (function () {
try {
return typeof navigator.userAgent === 'string' &&
typeof document.querySelector('body') === 'object' &&
typeof XMLHttpRequest.prototype.open === 'function' &&
'browser';
} catch (errorCaughtBrowser) {
return module.exports &&
typeof process.versions.node === 'string' &&
typeof require('http').createServer === 'function' &&
'node';
}
}());
// init global
local.global = local.modeJs === 'browser'
? window
: global;
// init utility2_rollup
local = local.global.utility2_rollup || (local.modeJs === 'browser'
? local.global.utility2_npmtest_svg_js
: global.utility2_moduleExports);
// export local
local.global.local = local;
}());
switch (local.modeJs) {
// post-init
// run browser js-env code - post-init
/* istanbul ignore next */
case 'browser':
local.testRunBrowser = function (event) {
Eif (!event || (event &&
event.currentTarget &&
event.currentTarget.className &&
event.currentTarget.className.includes &&
event.currentTarget.className.includes('onreset'))) {
// reset output
Array.from(
document.querySelectorAll('body > .resettable')
).forEach(function (element) {
switch (element.tagName) {
case 'INPUT':
case 'TEXTAREA':
element.value = '';
break;
default:
element.textContent = '';
}
});
}
switch (event && event.currentTarget && event.currentTarget.id) {
case 'testRunButton1':
// show tests
Eif (document.querySelector('#testReportDiv1').style.display === 'none') {
document.querySelector('#testReportDiv1').style.display = 'block';
document.querySelector('#testRunButton1').textContent =
'hide internal test';
local.modeTest = true;
local.testRunDefault(local);
// hide tests
} else {
document.querySelector('#testReportDiv1').style.display = 'none';
document.querySelector('#testRunButton1').textContent = 'run internal test';
}
break;
// custom-case
default:
break;
}
Iif (document.querySelector('#inputTextareaEval1') && (!event || (event &&
event.currentTarget &&
event.currentTarget.className &&
event.currentTarget.className.includes &&
event.currentTarget.className.includes('oneval')))) {
// try to eval input-code
try {
/*jslint evil: true*/
eval(document.querySelector('#inputTextareaEval1').value);
} catch (errorCaught) {
console.error(errorCaught);
}
}
};
// log stderr and stdout to #outputTextareaStdout1
['error', 'log'].forEach(function (key) {
console[key + '_original'] = console[key];
console[key] = function () {
var element;
console[key + '_original'].apply(console, arguments);
element = document.querySelector('#outputTextareaStdout1');
Iif (!element) {
return;
}
// append text to #outputTextareaStdout1
element.value += Array.from(arguments).map(function (arg) {
return typeof arg === 'string'
? arg
: JSON.stringify(arg, null, 4);
}).join(' ') + '\n';
// scroll textarea to bottom
element.scrollTop = element.scrollHeight;
};
});
// init event-handling
['change', 'click', 'keyup'].forEach(function (event) {
Array.from(document.querySelectorAll('.on' + event)).forEach(function (element) {
element.addEventListener(event, local.testRunBrowser);
});
});
// run tests
local.testRunBrowser();
break;
// run node js-env code - post-init
/* istanbul ignore next */
case 'node':
// export local
module.exports = local;
// require modules
local.fs = require('fs');
local.http = require('http');
local.url = require('url');
// init assets
local.assetsDict = local.assetsDict || {};
/* jslint-ignore-begin */
local.assetsDict['/assets.index.template.html'] = '\
<!doctype html>\n\
<html lang="en">\n\
<head>\n\
<meta charset="UTF-8">\n\
<meta name="viewport" content="width=device-width, initial-scale=1">\n\
<title>{{env.npm_package_name}} (v{{env.npm_package_version}})</title>\n\
<style>\n\
/*csslint\n\
box-sizing: false,\n\
universal-selector: false\n\
*/\n\
* {\n\
box-sizing: border-box;\n\
}\n\
body {\n\
background: #dde;\n\
font-family: Arial, Helvetica, sans-serif;\n\
margin: 2rem;\n\
}\n\
body > * {\n\
margin-bottom: 1rem;\n\
}\n\
.utility2FooterDiv {\n\
margin-top: 20px;\n\
text-align: center;\n\
}\n\
</style>\n\
<style>\n\
/*csslint\n\
*/\n\
textarea {\n\
font-family: monospace;\n\
height: 10rem;\n\
width: 100%;\n\
}\n\
textarea[readonly] {\n\
background: #ddd;\n\
}\n\
</style>\n\
</head>\n\
<body>\n\
<!-- utility2-comment\n\
<div id="ajaxProgressDiv1" style="background: #d00; height: 2px; left: 0; margin: 0; padding: 0; position: fixed; top: 0; transition: background 0.5s, width 1.5s; width: 25%;"></div>\n\
utility2-comment -->\n\
<h1>\n\
<!-- utility2-comment\n\
<a\n\
{{#if env.npm_package_homepage}}\n\
href="{{env.npm_package_homepage}}"\n\
{{/if env.npm_package_homepage}}\n\
target="_blank"\n\
>\n\
utility2-comment -->\n\
{{env.npm_package_name}} (v{{env.npm_package_version}})\n\
<!-- utility2-comment\n\
</a>\n\
utility2-comment -->\n\
</h1>\n\
<h3>{{env.npm_package_description}}</h3>\n\
<!-- utility2-comment\n\
<h4><a download href="assets.app.js">download standalone app</a></h4>\n\
<button class="onclick onreset" id="testRunButton1">run internal test</button><br>\n\
<div id="testReportDiv1" style="display: none;"></div>\n\
utility2-comment -->\n\
\n\
\n\
\n\
<label>stderr and stdout</label>\n\
<textarea class="resettable" id="outputTextareaStdout1" readonly></textarea>\n\
<!-- utility2-comment\n\
{{#if isRollup}}\n\
<script src="assets.app.js"></script>\n\
{{#unless isRollup}}\n\
utility2-comment -->\n\
<script src="assets.utility2.rollup.js"></script>\n\
<script src="jsonp.utility2._stateInit?callback=window.utility2._stateInit"></script>\n\
<script src="assets.npmtest_svg_js.rollup.js"></script>\n\
<script src="assets.example.js"></script>\n\
<script src="assets.test.js"></script>\n\
<!-- utility2-comment\n\
{{/if isRollup}}\n\
utility2-comment -->\n\
<div class="utility2FooterDiv">\n\
[ this app was created with\n\
<a href="https://github.com/kaizhu256/node-utility2" target="_blank">utility2</a>\n\
]\n\
</div>\n\
</body>\n\
</html>\n\
';
/* jslint-ignore-end */
Iif (local.templateRender) {
local.assetsDict['/'] = local.templateRender(
local.assetsDict['/assets.index.template.html'],
{
env: local.objectSetDefault(local.env, {
npm_package_description: 'the greatest app in the world!',
npm_package_name: 'my-app',
npm_package_nameAlias: 'my_app',
npm_package_version: '0.0.1'
})
}
);
} else {
local.assetsDict['/'] = local.assetsDict['/assets.index.template.html']
.replace((/\{\{env\.(\w+?)\}\}/g), function (match0, match1) {
// jslint-hack
String(match0);
switch (match1) {
case 'npm_package_description':
return 'the greatest app in the world!';
case 'npm_package_name':
return 'my-app';
case 'npm_package_nameAlias':
return 'my_app';
case 'npm_package_version':
return '0.0.1';
}
});
}
// run the cli
Eif (local.global.utility2_rollup || module !== require.main) {
break;
}
local.assetsDict['/assets.example.js'] =
local.assetsDict['/assets.example.js'] ||
local.fs.readFileSync(__filename, 'utf8');
// bug-workaround - long $npm_package_buildCustomOrg
/* jslint-ignore-begin */
local.assetsDict['/assets.npmtest_svg_js.rollup.js'] =
local.assetsDict['/assets.npmtest_svg_js.rollup.js'] ||
local.fs.readFileSync(
local.npmtest_svg_js.__dirname + '/lib.npmtest_svg_js.js',
'utf8'
).replace((/^#!/), '//');
/* jslint-ignore-end */
local.assetsDict['/favicon.ico'] = local.assetsDict['/favicon.ico'] || '';
// if $npm_config_timeout_exit exists,
// then exit this process after $npm_config_timeout_exit ms
if (Number(process.env.npm_config_timeout_exit)) {
setTimeout(process.exit, Number(process.env.npm_config_timeout_exit));
}
// start server
if (local.global.utility2_serverHttp1) {
break;
}
process.env.PORT = process.env.PORT || '8081';
console.error('server starting on port ' + process.env.PORT);
local.http.createServer(function (request, response) {
request.urlParsed = local.url.parse(request.url);
if (local.assetsDict[request.urlParsed.pathname] !== undefined) {
response.end(local.assetsDict[request.urlParsed.pathname]);
return;
}
response.statusCode = 404;
response.end();
}).listen(process.env.PORT);
break;
}
}());
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | 2 2 2 2 2 2 2 1 2 2 2 2 1 1 1 1 | /* istanbul instrument in package npmtest_svg_js */
/*jslint
bitwise: true,
browser: true,
maxerr: 8,
maxlen: 96,
node: true,
nomen: true,
regexp: true,
stupid: true
*/
(function () {
'use strict';
var local;
// run shared js-env code - pre-init
(function () {
// init local
local = {};
// init modeJs
local.modeJs = (function () {
try {
return typeof navigator.userAgent === 'string' &&
typeof document.querySelector('body') === 'object' &&
typeof XMLHttpRequest.prototype.open === 'function' &&
'browser';
} catch (errorCaughtBrowser) {
return module.exports &&
typeof process.versions.node === 'string' &&
typeof require('http').createServer === 'function' &&
'node';
}
}());
// init global
local.global = local.modeJs === 'browser'
? window
: global;
// init utility2_rollup
local = local.global.utility2_rollup || local;
// init lib
local.local = local.npmtest_svg_js = local;
// init exports
if (local.modeJs === 'browser') {
local.global.utility2_npmtest_svg_js = local;
} else {
module.exports = local;
module.exports.__dirname = __dirname;
module.exports.module = module;
}
}());
}());
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 | 2 2 2 2 2 2 2 1 2 2 1 1 1 1 2 2 2 2 1 1 2 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 1 2 2 1 2 2 1 2 2 1 1 1 1 1 | /* istanbul instrument in package npmtest_svg_js */
/*jslint
bitwise: true,
browser: true,
maxerr: 8,
maxlen: 96,
node: true,
nomen: true,
regexp: true,
stupid: true
*/
(function () {
'use strict';
var local;
// run shared js-env code - pre-init
(function () {
// init local
local = {};
// init modeJs
local.modeJs = (function () {
try {
return typeof navigator.userAgent === 'string' &&
typeof document.querySelector('body') === 'object' &&
typeof XMLHttpRequest.prototype.open === 'function' &&
'browser';
} catch (errorCaughtBrowser) {
return module.exports &&
typeof process.versions.node === 'string' &&
typeof require('http').createServer === 'function' &&
'node';
}
}());
// init global
local.global = local.modeJs === 'browser'
? window
: global;
switch (local.modeJs) {
// re-init local from window.local
case 'browser':
local = local.global.utility2.objectSetDefault(
local.global.utility2_rollup || local.global.local,
local.global.utility2
);
break;
// re-init local from example.js
case 'node':
local = (local.global.utility2_rollup || require('utility2'))
.requireReadme();
break;
}
// export local
local.global.local = local;
}());
// run shared js-env code - function
(function () {
return;
}());
switch (local.modeJs) {
// run browser js-env code - function
case 'browser':
break;
// run node js-env code - function
case 'node':
break;
}
// run shared js-env code - post-init
(function () {
return;
}());
switch (local.modeJs) {
// run browser js-env code - post-init
case 'browser':
local.testCase_browser_nullCase = local.testCase_browser_nullCase || function (
options,
onError
) {
/*
* this function will test browsers's null-case handling-behavior-behavior
*/
onError(null, options);
};
// run tests
local.nop(local.modeTest &&
document.querySelector('#testRunButton1') &&
document.querySelector('#testRunButton1').click());
break;
// run node js-env code - post-init
/* istanbul ignore next */
case 'node':
local.testCase_buildApidoc_default = local.testCase_buildApidoc_default || function (
options,
onError
) {
/*
* this function will test buildApidoc's default handling-behavior-behavior
*/
options = { modulePathList: module.paths };
local.buildApidoc(options, onError);
};
local.testCase_buildApp_default = local.testCase_buildApp_default || function (
options,
onError
) {
/*
* this function will test buildApp's default handling-behavior-behavior
*/
local.testCase_buildReadme_default(options, local.onErrorThrow);
local.testCase_buildLib_default(options, local.onErrorThrow);
local.testCase_buildTest_default(options, local.onErrorThrow);
local.testCase_buildCustomOrg_default(options, local.onErrorThrow);
options = [];
local.buildApp(options, onError);
};
local.testCase_buildCustomOrg_default = local.testCase_buildCustomOrg_default ||
function (options, onError) {
/*
* this function will test buildCustomOrg's default handling-behavior
*/
options = {};
local.buildCustomOrg(options, onError);
};
local.testCase_buildLib_default = local.testCase_buildLib_default || function (
options,
onError
) {
/*
* this function will test buildLib's default handling-behavior
*/
options = {};
local.buildLib(options, onError);
};
local.testCase_buildReadme_default = local.testCase_buildReadme_default || function (
options,
onError
) {
/*
* this function will test buildReadme's default handling-behavior-behavior
*/
options = {};
local.buildReadme(options, onError);
};
local.testCase_buildTest_default = local.testCase_buildTest_default || function (
options,
onError
) {
/*
* this function will test buildTest's default handling-behavior
*/
options = {};
local.buildTest(options, onError);
};
local.testCase_webpage_default = local.testCase_webpage_default || function (
options,
onError
) {
/*
* this function will test webpage's default handling-behavior
*/
options = { modeCoverageMerge: true, url: local.serverLocalHost + '?modeTest=1' };
local.browserTest(options, onError);
};
// run test-server
local.testRunServer(local);
break;
}
}());
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| gulpfile.js | 8.33% | (1 / 12) | 100% | (0 / 0) | 0% | (0 / 3) | 8.33% | (1 / 12) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 | 2 | var del = require('del')
, gulp = require('gulp')
, chmod = require('gulp-chmod')
, concat = require('gulp-concat')
, header = require('gulp-header')
, rename = require('gulp-rename')
, size = require('gulp-size')
, trim = require('gulp-trimlines')
, uglify = require('gulp-uglify')
, wrapUmd = require('gulp-wrap')
, request = require('request')
, fs = require('fs')
, pkg = require('./package.json')
var headerLong = ['/*!'
, '* <%= pkg.name %> - <%= pkg.description %>'
, '* @version <%= pkg.version %>'
, '* <%= pkg.homepage %>'
, '*'
, '* @copyright <%= pkg.author %>'
, '* @license <%= pkg.license %>'
, '*'
, '* BUILT: <%= pkg.buildDate %>'
, '*/;'
, ''].join('\n')
var headerShort = '/*! <%= pkg.name %> v<%= pkg.version %> <%= pkg.license %>*/;'
// all files in the right order (currently we don't use any dependency management system)
var parts = [
'src/svg.js'
, 'src/regex.js'
, 'src/utilities.js'
, 'src/default.js'
, 'src/color.js'
, 'src/array.js'
, 'src/pointarray.js'
, 'src/patharray.js'
, 'src/number.js'
, 'src/element.js'
, 'src/fx.js'
, 'src/boxes.js'
, 'src/matrix.js'
, 'src/point.js'
, 'src/attr.js'
, 'src/transform.js'
, 'src/style.js'
, 'src/parent.js'
, 'src/ungroup.js'
, 'src/container.js'
, 'src/viewbox.js'
, 'src/event.js'
, 'src/defs.js'
, 'src/group.js'
, 'src/arrange.js'
, 'src/mask.js'
, 'src/clip.js'
, 'src/gradient.js'
, 'src/pattern.js'
, 'src/doc.js'
, 'src/shape.js'
, 'src/bare.js'
, 'src/symbol.js'
, 'src/use.js'
, 'src/rect.js'
, 'src/ellipse.js'
, 'src/line.js'
, 'src/poly.js'
, 'src/pointed.js'
, 'src/path.js'
, 'src/image.js'
, 'src/text.js'
, 'src/textpath.js'
, 'src/nested.js'
, 'src/hyperlink.js'
, 'src/marker.js'
, 'src/sugar.js'
, 'src/set.js'
, 'src/data.js'
, 'src/memory.js'
, 'src/selector.js'
, 'src/helpers.js'
, 'src/polyfill.js'
]
gulp.task('clean', function() {
return del([ 'dist/*' ])
})
/**
* Compile everything in /src to one unified file in the order defined in the MODULES constant
* wrap the whole thing in a UMD wrapper (@see https://github.com/umdjs/umd)
* add the license information to the header plus the build time stamp
*/
gulp.task('unify', ['clean'], function() {
pkg.buildDate = Date()
return gulp.src(parts)
.pipe(concat('svg.js', { newLine: '\n' }))
// wrap the whole thing in an immediate function call
.pipe(wrapUmd({ src: 'src/umd.js'}))
.pipe(header(headerLong, { pkg: pkg }))
.pipe(trim({ leading: false }))
.pipe(chmod(0o644))
.pipe(gulp.dest('dist'))
.pipe(size({ showFiles: true, title: 'Full' }))
})
/**
* uglify the file and show the size of the result
* add the license info
* show the gzipped file size
*/
gulp.task('minify', ['unify'], function() {
return gulp.src('dist/svg.js')
.pipe(uglify())
.pipe(rename({ suffix:'.min' }))
.pipe(size({ showFiles: true, title: 'Minified' }))
.pipe(header(headerShort, { pkg: pkg }))
.pipe(chmod(0o644))
.pipe(gulp.dest('dist'))
.pipe(size({ showFiles: true, gzip: true, title: 'Gzipped' }))
})
gulp.task('default', ['clean', 'unify', 'minify'])
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| karma.conf.js | 33.33% | (1 / 3) | 100% | (0 / 0) | 0% | (0 / 2) | 33.33% | (1 / 3) | |
| karma.quick.js | 50% | (1 / 2) | 100% | (0 / 0) | 0% | (0 / 1) | 50% | (1 / 2) | |
| pretest.js | 30.77% | (4 / 13) | 0% | (0 / 2) | 50% | (1 / 2) | 30.77% | (4 / 13) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 | 1 | // Karma configuration // Generated on Tue Oct 04 2016 13:53:46 GMT+0200 (CEST) module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '../', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['jasmine'], // list of files / patterns to load in the browser files: [ '.config/pretest.js', { pattern: 'spec/fixture.css', included: false, served: true }, { pattern: 'spec/fixture.svg', included: false, served: true }, { pattern: 'spec/fixtures/pixel.png', included: false, served: true }, 'dist/svg.js', 'spec/spec/**/*.js' ], proxies: { '/fixtures/': '/base/spec/fixtures/' }, // list of files to exclude exclude: [], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { 'dist/svg.js': ['coverage'] }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress', 'coverage'], // configure the coverage reporter coverageReporter: { // Specify a reporter type. type: 'lcov', dir: 'coverage/', subdir: function(browser) { // normalization process to keep a consistent browser name accross different OS return browser.toLowerCase().split(/[ /-]/)[0]; // output the results into: './coverage/firefox/' } }, // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: false, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['Firefox'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: false, // Concurrency level // how many browser should be started simultaneous concurrency: Infinity }) } |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 | 1 | // Karma configuration // Generated on Tue Oct 04 2016 13:53:46 GMT+0200 (CEST) module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '../', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['jasmine'], // list of files / patterns to load in the browser files: [ '.config/pretest.js', { pattern: 'spec/fixture.css', included: false, served: true }, { pattern: 'spec/fixture.svg', included: false, served: true }, 'dist/svg.js', 'spec/spec/**/*.js' ], // list of files to exclude exclude: [], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: {}, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress'], // configure the coverage reporter coverageReporter: {}, // web server port port: 9875, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_ERROR, // enable / disable watching file and executing tests whenever any file changes autoWatch: false, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['PhantomJS'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: true, // Concurrency level // how many browser should be started simultaneous concurrency: 1 }) } |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 1 1 2 2 | 'use strict' function get(uri) { var xhr = new XMLHttpRequest() xhr.open('GET', uri, false) xhr.send() if(xhr.status !== 200) console.error('SVG.js fixture could not be loaded. Tests will fail.') return xhr.responseText } function main() { var style = document.createElement("style") document.head.appendChild(style) style.sheet.insertRule( get('/base/spec/fixture.css'), 0 ) document.body.innerHTML = get('/base/spec/fixture.svg') } main() |
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| svg.bench.js | 6.25% | (2 / 32) | 0% | (0 / 4) | 10% | (1 / 10) | 6.25% | (2 / 32) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 | 2 2 | ;( function() {
SVG.bench = {
// Initalize test store
_chain: []
, _before: function() {}
, _after: function() {}
, draw: SVG('draw')
, snap: Snap(100, 100)
, raw: document.getElementById('native')
// Add descriptor
, describe: function(name, closure) {
this._chain.push({
name: name
, run: closure
})
return this
}
// Add test
, test: function(name, run) {
// run test
var start = ( new Date ).getTime()
run()
this.write( name, ( new Date ).getTime() - start )
// clear everything
this.clear()
}
// Skip test
, skip: function(name, run) {
this.write( name, false )
}
// Run tests
, run: function() {
this.pad()
for (var h, i = 0, il = this._chain.length; i < il; i++) {
var h = document.createElement('h1')
h.innerHTML = this._chain[i].name
this.pad().appendChild(h)
this._chain[i].run(this)
}
}
// Write result
, write: function(name, ms) {
var test = document.createElement('div')
if (typeof ms === 'number') {
test.className = 'test'
test.innerHTML = '<span class="name">' + name + '</span> completed in <span class="ms">' + ms + 'ms</span>'
} else {
test.className = 'test skipped'
test.innerHTML = name + ' (skipped)'
}
this.pad().appendChild(test)
return this
}
// Reference writable element
, pad: function() {
var pad = document.getElementById('pad')
if (!pad) {
pad = document.createElement('div')
document.getElementsByTagName('body')[0].appendChild(pad)
}
return pad
}
// Clear canvasses
, clear: function() {
while(this.raw.hasChildNodes())
this.raw.removeChild(this.raw.lastChild)
this.draw.clear()
this.snap.clear()
}
}
})();
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| svg.js | 1.3% | (25 / 1922) | 0.74% | (9 / 1221) | 0.6% | (3 / 503) | 1.3% | (24 / 1848) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | /*!
* svg.js - A lightweight library for manipulating and animating SVG.
* @version 2.6.0
* https://svgdotjs.github.io/
*
* @copyright Wout Fierens <wout@mick-wout.com>
* @license MIT
*
* BUILT: Fri Apr 21 2017 12:48:06 GMT+0200 (Mitteleuropäische Sommerzeit)
*/;
(function(root, factory) {
/* istanbul ignore next */
Iif (typeof define === 'function' && define.amd) {
define(function(){
return factory(root, root.document)
})
} else Eif (typeof exports === 'object') {
module.exports = root.document ? factory(root, root.document) : function(w){ return factory(w, w.document) }
} else {
root.SVG = factory(root, root.document)
}
}(typeof window !== "undefined" ? window : this, function(window, document) {
// The main wrapping element
var SVG = this.SVG = function(element) {
if (SVG.supported) {
element = new SVG.Doc(element)
if(!SVG.parser.draw)
SVG.prepare()
return element
}
}
// Default namespaces
SVG.ns = 'http://www.w3.org/2000/svg'
SVG.xmlns = 'http://www.w3.org/2000/xmlns/'
SVG.xlink = 'http://www.w3.org/1999/xlink'
SVG.svgjs = 'http://svgjs.com/svgjs'
// Svg support test
SVG.supported = (function() {
return !! document.createElementNS &&
!! document.createElementNS(SVG.ns,'svg').createSVGRect
})()
// Don't bother to continue if SVG is not supported
if (!SVG.supported) return false
// Element id sequence
SVG.did = 1000
// Get next named element id
SVG.eid = function(name) {
return 'Svgjs' + capitalize(name) + (SVG.did++)
}
// Method for element creation
SVG.create = function(name) {
// create element
var element = document.createElementNS(this.ns, name)
// apply unique id
element.setAttribute('id', this.eid(name))
return element
}
// Method for extending objects
SVG.extend = function() {
var modules, methods, key, i
// Get list of modules
modules = [].slice.call(arguments)
// Get object with extensions
methods = modules.pop()
for (i = modules.length - 1; i >= 0; i--)
if (modules[i])
for (key in methods)
modules[i].prototype[key] = methods[key]
// Make sure SVG.Set inherits any newly added methods
if (SVG.Set && SVG.Set.inherit)
SVG.Set.inherit()
}
// Invent new element
SVG.invent = function(config) {
// Create element initializer
var initializer = typeof config.create == 'function' ?
config.create :
function() {
this.constructor.call(this, SVG.create(config.create))
}
// Inherit prototype
if (config.inherit)
initializer.prototype = new config.inherit
// Extend with methods
if (config.extend)
SVG.extend(initializer, config.extend)
// Attach construct method to parent
if (config.construct)
SVG.extend(config.parent || SVG.Container, config.construct)
return initializer
}
// Adopt existing svg elements
SVG.adopt = function(node) {
// check for presence of node
if (!node) return null
// make sure a node isn't already adopted
if (node.instance) return node.instance
// initialize variables
var element
// adopt with element-specific settings
if (node.nodeName == 'svg')
element = node.parentNode instanceof window.SVGElement ? new SVG.Nested : new SVG.Doc
else if (node.nodeName == 'linearGradient')
element = new SVG.Gradient('linear')
else if (node.nodeName == 'radialGradient')
element = new SVG.Gradient('radial')
else if (SVG[capitalize(node.nodeName)])
element = new SVG[capitalize(node.nodeName)]
else
element = new SVG.Element(node)
// ensure references
element.type = node.nodeName
element.node = node
node.instance = element
// SVG.Class specific preparations
if (element instanceof SVG.Doc)
element.namespace().defs()
// pull svgjs data from the dom (getAttributeNS doesn't work in html5)
element.setData(JSON.parse(node.getAttribute('svgjs:data')) || {})
return element
}
// Initialize parsing element
SVG.prepare = function() {
// Select document body and create invisible svg element
var body = document.getElementsByTagName('body')[0]
, draw = (body ? new SVG.Doc(body) : SVG.adopt(document.documentElement).nested()).size(2, 0)
// Create parser object
SVG.parser = {
body: body || document.documentElement
, draw: draw.style('opacity:0;position:absolute;left:-100%;top:-100%;overflow:hidden').node
, poly: draw.polyline().node
, path: draw.path().node
, native: SVG.create('svg')
}
}
SVG.parser = {
native: SVG.create('svg')
}
document.addEventListener('DOMContentLoaded', function() {
if(!SVG.parser.draw)
SVG.prepare()
}, false)
// Storage for regular expressions
SVG.regex = {
// Parse unit value
numberAndUnit: /^([+-]?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?)([a-z%]*)$/i
// Parse hex value
, hex: /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i
// Parse rgb value
, rgb: /rgb\((\d+),(\d+),(\d+)\)/
// Parse reference id
, reference: /#([a-z0-9\-_]+)/i
// splits a transformation chain
, transforms: /\)\s*,?\s*/
// Whitespace
, whitespace: /\s/g
// Test hex value
, isHex: /^#[a-f0-9]{3,6}$/i
// Test rgb value
, isRgb: /^rgb\(/
// Test css declaration
, isCss: /[^:]+:[^;]+;?/
// Test for blank string
, isBlank: /^(\s+)?$/
// Test for numeric string
, isNumber: /^[+-]?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i
// Test for percent value
, isPercent: /^-?[\d\.]+%$/
// Test for image url
, isImage: /\.(jpg|jpeg|png|gif|svg)(\?[^=]+.*)?/i
// split at whitespace and comma
, delimiter: /[\s,]+/
// The following regex are used to parse the d attribute of a path
// Matches all hyphens which are not after an exponent
, hyphen: /([^e])\-/gi
// Replaces and tests for all path letters
, pathLetters: /[MLHVCSQTAZ]/gi
// yes we need this one, too
, isPathLetter: /[MLHVCSQTAZ]/i
// matches 0.154.23.45
, numbersWithDots: /((\d?\.\d+(?:e[+-]?\d+)?)((?:\.\d+(?:e[+-]?\d+)?)+))+/gi
// matches .
, dots: /\./g
}
SVG.utils = {
// Map function
map: function(array, block) {
var i
, il = array.length
, result = []
for (i = 0; i < il; i++)
result.push(block(array[i]))
return result
}
// Filter function
, filter: function(array, block) {
var i
, il = array.length
, result = []
for (i = 0; i < il; i++)
if (block(array[i]))
result.push(array[i])
return result
}
// Degrees to radians
, radians: function(d) {
return d % 360 * Math.PI / 180
}
// Radians to degrees
, degrees: function(r) {
return r * 180 / Math.PI % 360
}
, filterSVGElements: function(nodes) {
return this.filter( nodes, function(el) { return el instanceof window.SVGElement })
}
}
SVG.defaults = {
// Default attribute values
attrs: {
// fill and stroke
'fill-opacity': 1
, 'stroke-opacity': 1
, 'stroke-width': 0
, 'stroke-linejoin': 'miter'
, 'stroke-linecap': 'butt'
, fill: '#000000'
, stroke: '#000000'
, opacity: 1
// position
, x: 0
, y: 0
, cx: 0
, cy: 0
// size
, width: 0
, height: 0
// radius
, r: 0
, rx: 0
, ry: 0
// gradient
, offset: 0
, 'stop-opacity': 1
, 'stop-color': '#000000'
// text
, 'font-size': 16
, 'font-family': 'Helvetica, Arial, sans-serif'
, 'text-anchor': 'start'
}
}
// Module for color convertions
SVG.Color = function(color) {
var match
// initialize defaults
this.r = 0
this.g = 0
this.b = 0
if(!color) return
// parse color
if (typeof color === 'string') {
if (SVG.regex.isRgb.test(color)) {
// get rgb values
match = SVG.regex.rgb.exec(color.replace(SVG.regex.whitespace,''))
// parse numeric values
this.r = parseInt(match[1])
this.g = parseInt(match[2])
this.b = parseInt(match[3])
} else if (SVG.regex.isHex.test(color)) {
// get hex values
match = SVG.regex.hex.exec(fullHex(color))
// parse numeric values
this.r = parseInt(match[1], 16)
this.g = parseInt(match[2], 16)
this.b = parseInt(match[3], 16)
}
} else if (typeof color === 'object') {
this.r = color.r
this.g = color.g
this.b = color.b
}
}
SVG.extend(SVG.Color, {
// Default to hex conversion
toString: function() {
return this.toHex()
}
// Build hex value
, toHex: function() {
return '#'
+ compToHex(this.r)
+ compToHex(this.g)
+ compToHex(this.b)
}
// Build rgb value
, toRgb: function() {
return 'rgb(' + [this.r, this.g, this.b].join() + ')'
}
// Calculate true brightness
, brightness: function() {
return (this.r / 255 * 0.30)
+ (this.g / 255 * 0.59)
+ (this.b / 255 * 0.11)
}
// Make color morphable
, morph: function(color) {
this.destination = new SVG.Color(color)
return this
}
// Get morphed color at given position
, at: function(pos) {
// make sure a destination is defined
if (!this.destination) return this
// normalise pos
pos = pos < 0 ? 0 : pos > 1 ? 1 : pos
// generate morphed color
return new SVG.Color({
r: ~~(this.r + (this.destination.r - this.r) * pos)
, g: ~~(this.g + (this.destination.g - this.g) * pos)
, b: ~~(this.b + (this.destination.b - this.b) * pos)
})
}
})
// Testers
// Test if given value is a color string
SVG.Color.test = function(color) {
color += ''
return SVG.regex.isHex.test(color)
|| SVG.regex.isRgb.test(color)
}
// Test if given value is a rgb object
SVG.Color.isRgb = function(color) {
return color && typeof color.r == 'number'
&& typeof color.g == 'number'
&& typeof color.b == 'number'
}
// Test if given value is a color
SVG.Color.isColor = function(color) {
return SVG.Color.isRgb(color) || SVG.Color.test(color)
}
// Module for array conversion
SVG.Array = function(array, fallback) {
array = (array || []).valueOf()
// if array is empty and fallback is provided, use fallback
if (array.length == 0 && fallback)
array = fallback.valueOf()
// parse array
this.value = this.parse(array)
}
SVG.extend(SVG.Array, {
// Make array morphable
morph: function(array) {
this.destination = this.parse(array)
// normalize length of arrays
if (this.value.length != this.destination.length) {
var lastValue = this.value[this.value.length - 1]
, lastDestination = this.destination[this.destination.length - 1]
while(this.value.length > this.destination.length)
this.destination.push(lastDestination)
while(this.value.length < this.destination.length)
this.value.push(lastValue)
}
return this
}
// Clean up any duplicate points
, settle: function() {
// find all unique values
for (var i = 0, il = this.value.length, seen = []; i < il; i++)
if (seen.indexOf(this.value[i]) == -1)
seen.push(this.value[i])
// set new value
return this.value = seen
}
// Get morphed array at given position
, at: function(pos) {
// make sure a destination is defined
if (!this.destination) return this
// generate morphed array
for (var i = 0, il = this.value.length, array = []; i < il; i++)
array.push(this.value[i] + (this.destination[i] - this.value[i]) * pos)
return new SVG.Array(array)
}
// Convert array to string
, toString: function() {
return this.value.join(' ')
}
// Real value
, valueOf: function() {
return this.value
}
// Parse whitespace separated string
, parse: function(array) {
array = array.valueOf()
// if already is an array, no need to parse it
if (Array.isArray(array)) return array
return this.split(array)
}
// Strip unnecessary whitespace
, split: function(string) {
return string.trim().split(SVG.regex.delimiter).map(parseFloat)
}
// Reverse array
, reverse: function() {
this.value.reverse()
return this
}
, clone: function() {
var clone = new this.constructor()
clone.value = array_clone(this.value)
return clone
}
})
// Poly points array
SVG.PointArray = function(array, fallback) {
SVG.Array.call(this, array, fallback || [[0,0]])
}
// Inherit from SVG.Array
SVG.PointArray.prototype = new SVG.Array
SVG.PointArray.prototype.constructor = SVG.PointArray
SVG.extend(SVG.PointArray, {
// Convert array to string
toString: function() {
// convert to a poly point string
for (var i = 0, il = this.value.length, array = []; i < il; i++)
array.push(this.value[i].join(','))
return array.join(' ')
}
// Convert array to line object
, toLine: function() {
return {
x1: this.value[0][0]
, y1: this.value[0][1]
, x2: this.value[1][0]
, y2: this.value[1][1]
}
}
// Get morphed array at given position
, at: function(pos) {
// make sure a destination is defined
if (!this.destination) return this
// generate morphed point string
for (var i = 0, il = this.value.length, array = []; i < il; i++)
array.push([
this.value[i][0] + (this.destination[i][0] - this.value[i][0]) * pos
, this.value[i][1] + (this.destination[i][1] - this.value[i][1]) * pos
])
return new SVG.PointArray(array)
}
// Parse point string and flat array
, parse: function(array) {
var points = []
array = array.valueOf()
// if it is an array
if (Array.isArray(array)) {
// and it is not flat, there is no need to parse it
if(Array.isArray(array[0])) {
return array
}
} else { // Else, it is considered as a string
// parse points
array = array.trim().split(SVG.regex.delimiter).map(parseFloat)
}
// validate points - https://svgwg.org/svg2-draft/shapes.html#DataTypePoints
// Odd number of coordinates is an error. In such cases, drop the last odd coordinate.
if (array.length % 2 !== 0) array.pop()
// wrap points in two-tuples and parse points as floats
for(var i = 0, len = array.length; i < len; i = i + 2)
points.push([ array[i], array[i+1] ])
return points
}
// Move point string
, move: function(x, y) {
var box = this.bbox()
// get relative offset
x -= box.x
y -= box.y
// move every point
if (!isNaN(x) && !isNaN(y))
for (var i = this.value.length - 1; i >= 0; i--)
this.value[i] = [this.value[i][0] + x, this.value[i][1] + y]
return this
}
// Resize poly string
, size: function(width, height) {
var i, box = this.bbox()
// recalculate position of all points according to new size
for (i = this.value.length - 1; i >= 0; i--) {
if(box.width) this.value[i][0] = ((this.value[i][0] - box.x) * width) / box.width + box.x
if(box.height) this.value[i][1] = ((this.value[i][1] - box.y) * height) / box.height + box.y
}
return this
}
// Get bounding box of points
, bbox: function() {
SVG.parser.poly.setAttribute('points', this.toString())
return SVG.parser.poly.getBBox()
}
})
var pathHandlers = {
M: function(c, p, p0) {
p.x = p0.x = c[0]
p.y = p0.y = c[1]
return ['M', p.x, p.y]
},
L: function(c, p) {
p.x = c[0]
p.y = c[1]
return ['L', c[0], c[1]]
},
H: function(c, p) {
p.x = c[0]
return ['H', c[0]]
},
V: function(c, p) {
p.y = c[0]
return ['V', c[0]]
},
C: function(c, p) {
p.x = c[4]
p.y = c[5]
return ['C', c[0], c[1], c[2], c[3], c[4], c[5]]
},
S: function(c, p) {
p.x = c[2]
p.y = c[3]
return ['S', c[0], c[1], c[2], c[3]]
},
Q: function(c, p) {
p.x = c[2]
p.y = c[3]
return ['Q', c[0], c[1], c[2], c[3]]
},
T: function(c, p) {
p.x = c[0]
p.y = c[1]
return ['T', c[0], c[1]]
},
Z: function(c, p, p0) {
p.x = p0.x
p.y = p0.y
return ['Z']
},
A: function(c, p) {
p.x = c[5]
p.y = c[6]
return ['A', c[0], c[1], c[2], c[3], c[4], c[5], c[6]]
}
}
var mlhvqtcsa = 'mlhvqtcsaz'.split('')
for(var i = 0, il = mlhvqtcsa.length; i < il; ++i){
pathHandlers[mlhvqtcsa[i]] = (function(i){
return function(c, p, p0) {
if(i == 'H') c[0] = c[0] + p.x
else if(i == 'V') c[0] = c[0] + p.y
else if(i == 'A'){
c[5] = c[5] + p.x,
c[6] = c[6] + p.y
}
else
for(var j = 0, jl = c.length; j < jl; ++j) {
c[j] = c[j] + (j%2 ? p.y : p.x)
}
return pathHandlers[i](c, p, p0)
}
})(mlhvqtcsa[i].toUpperCase())
}
// Path points array
SVG.PathArray = function(array, fallback) {
SVG.Array.call(this, array, fallback || [['M', 0, 0]])
}
// Inherit from SVG.Array
SVG.PathArray.prototype = new SVG.Array
SVG.PathArray.prototype.constructor = SVG.PathArray
SVG.extend(SVG.PathArray, {
// Convert array to string
toString: function() {
return arrayToString(this.value)
}
// Move path string
, move: function(x, y) {
// get bounding box of current situation
var box = this.bbox()
// get relative offset
x -= box.x
y -= box.y
if (!isNaN(x) && !isNaN(y)) {
// move every point
for (var l, i = this.value.length - 1; i >= 0; i--) {
l = this.value[i][0]
if (l == 'M' || l == 'L' || l == 'T') {
this.value[i][1] += x
this.value[i][2] += y
} else if (l == 'H') {
this.value[i][1] += x
} else if (l == 'V') {
this.value[i][1] += y
} else if (l == 'C' || l == 'S' || l == 'Q') {
this.value[i][1] += x
this.value[i][2] += y
this.value[i][3] += x
this.value[i][4] += y
if (l == 'C') {
this.value[i][5] += x
this.value[i][6] += y
}
} else if (l == 'A') {
this.value[i][6] += x
this.value[i][7] += y
}
}
}
return this
}
// Resize path string
, size: function(width, height) {
// get bounding box of current situation
var i, l, box = this.bbox()
// recalculate position of all points according to new size
for (i = this.value.length - 1; i >= 0; i--) {
l = this.value[i][0]
if (l == 'M' || l == 'L' || l == 'T') {
this.value[i][1] = ((this.value[i][1] - box.x) * width) / box.width + box.x
this.value[i][2] = ((this.value[i][2] - box.y) * height) / box.height + box.y
} else if (l == 'H') {
this.value[i][1] = ((this.value[i][1] - box.x) * width) / box.width + box.x
} else if (l == 'V') {
this.value[i][1] = ((this.value[i][1] - box.y) * height) / box.height + box.y
} else if (l == 'C' || l == 'S' || l == 'Q') {
this.value[i][1] = ((this.value[i][1] - box.x) * width) / box.width + box.x
this.value[i][2] = ((this.value[i][2] - box.y) * height) / box.height + box.y
this.value[i][3] = ((this.value[i][3] - box.x) * width) / box.width + box.x
this.value[i][4] = ((this.value[i][4] - box.y) * height) / box.height + box.y
if (l == 'C') {
this.value[i][5] = ((this.value[i][5] - box.x) * width) / box.width + box.x
this.value[i][6] = ((this.value[i][6] - box.y) * height) / box.height + box.y
}
} else if (l == 'A') {
// resize radii
this.value[i][1] = (this.value[i][1] * width) / box.width
this.value[i][2] = (this.value[i][2] * height) / box.height
// move position values
this.value[i][6] = ((this.value[i][6] - box.x) * width) / box.width + box.x
this.value[i][7] = ((this.value[i][7] - box.y) * height) / box.height + box.y
}
}
return this
}
// Test if the passed path array use the same path data commands as this path array
, equalCommands: function(pathArray) {
var i, il, equalCommands
pathArray = new SVG.PathArray(pathArray)
equalCommands = this.value.length === pathArray.value.length
for(i = 0, il = this.value.length; equalCommands && i < il; i++) {
equalCommands = this.value[i][0] === pathArray.value[i][0]
}
return equalCommands
}
// Make path array morphable
, morph: function(pathArray) {
pathArray = new SVG.PathArray(pathArray)
if(this.equalCommands(pathArray)) {
this.destination = pathArray
} else {
this.destination = null
}
return this
}
// Get morphed path array at given position
, at: function(pos) {
// make sure a destination is defined
if (!this.destination) return this
var sourceArray = this.value
, destinationArray = this.destination.value
, array = [], pathArray = new SVG.PathArray()
, i, il, j, jl
// Animate has specified in the SVG spec
// See: https://www.w3.org/TR/SVG11/paths.html#PathElement
for (i = 0, il = sourceArray.length; i < il; i++) {
array[i] = [sourceArray[i][0]]
for(j = 1, jl = sourceArray[i].length; j < jl; j++) {
array[i][j] = sourceArray[i][j] + (destinationArray[i][j] - sourceArray[i][j]) * pos
}
// For the two flags of the elliptical arc command, the SVG spec say:
// Flags and booleans are interpolated as fractions between zero and one, with any non-zero value considered to be a value of one/true
// Elliptical arc command as an array followed by corresponding indexes:
// ['A', rx, ry, x-axis-rotation, large-arc-flag, sweep-flag, x, y]
// 0 1 2 3 4 5 6 7
if(array[i][0] === 'A') {
array[i][4] = +(array[i][4] != 0)
array[i][5] = +(array[i][5] != 0)
}
}
// Directly modify the value of a path array, this is done this way for performance
pathArray.value = array
return pathArray
}
// Absolutize and parse path to array
, parse: function(array) {
// if it's already a patharray, no need to parse it
if (array instanceof SVG.PathArray) return array.valueOf()
// prepare for parsing
var i, x0, y0, s, seg, arr
, x = 0
, y = 0
, paramCnt = { 'M':2, 'L':2, 'H':1, 'V':1, 'C':6, 'S':4, 'Q':4, 'T':2, 'A':7 }
if(typeof array == 'string'){
array = array
.replace(SVG.regex.numbersWithDots, pathRegReplace) // convert 45.123.123 to 45.123 .123
.replace(SVG.regex.pathLetters, ' $& ') // put some room between letters and numbers
.replace(SVG.regex.hyphen, '$1 -') // add space before hyphen
.trim() // trim
.split(SVG.regex.delimiter) // split into array
}else{
array = array.reduce(function(prev, curr){
return [].concat.call(prev, curr)
}, [])
}
// array now is an array containing all parts of a path e.g. ['M', '0', '0', 'L', '30', '30' ...]
var arr = []
, p = new SVG.Point()
, p0 = new SVG.Point()
, index = 0
, len = array.length
do{
// Test if we have a path letter
if(SVG.regex.isPathLetter.test(array[index])){
s = array[index]
++index
// If last letter was a move command and we got no new, it defaults to [L]ine
}else if(s == 'M'){
s = 'L'
}else if(s == 'm'){
s = 'l'
}
arr.push(pathHandlers[s].call(null,
array.slice(index, (index = index + paramCnt[s.toUpperCase()])).map(parseFloat),
p, p0
)
)
}while(len > index)
return arr
}
// Get bounding box of path
, bbox: function() {
SVG.parser.path.setAttribute('d', this.toString())
return SVG.parser.path.getBBox()
}
})
// Module for unit convertions
SVG.Number = SVG.invent({
// Initialize
create: function(value, unit) {
// initialize defaults
this.value = 0
this.unit = unit || ''
// parse value
if (typeof value === 'number') {
// ensure a valid numeric value
this.value = isNaN(value) ? 0 : !isFinite(value) ? (value < 0 ? -3.4e+38 : +3.4e+38) : value
} else if (typeof value === 'string') {
unit = value.match(SVG.regex.numberAndUnit)
if (unit) {
// make value numeric
this.value = parseFloat(unit[1])
// normalize
if (unit[5] == '%')
this.value /= 100
else if (unit[5] == 's')
this.value *= 1000
// store unit
this.unit = unit[5]
}
} else {
if (value instanceof SVG.Number) {
this.value = value.valueOf()
this.unit = value.unit
}
}
}
// Add methods
, extend: {
// Stringalize
toString: function() {
return (
this.unit == '%' ?
~~(this.value * 1e8) / 1e6:
this.unit == 's' ?
this.value / 1e3 :
this.value
) + this.unit
}
, toJSON: function() {
return this.toString()
}
, // Convert to primitive
valueOf: function() {
return this.value
}
// Add number
, plus: function(number) {
number = new SVG.Number(number)
return new SVG.Number(this + number, this.unit || number.unit)
}
// Subtract number
, minus: function(number) {
number = new SVG.Number(number)
return new SVG.Number(this - number, this.unit || number.unit)
}
// Multiply number
, times: function(number) {
number = new SVG.Number(number)
return new SVG.Number(this * number, this.unit || number.unit)
}
// Divide number
, divide: function(number) {
number = new SVG.Number(number)
return new SVG.Number(this / number, this.unit || number.unit)
}
// Convert to different unit
, to: function(unit) {
var number = new SVG.Number(this)
if (typeof unit === 'string')
number.unit = unit
return number
}
// Make number morphable
, morph: function(number) {
this.destination = new SVG.Number(number)
if(number.relative) {
this.destination.value += this.value
}
return this
}
// Get morphed number at given position
, at: function(pos) {
// Make sure a destination is defined
if (!this.destination) return this
// Generate new morphed number
return new SVG.Number(this.destination)
.minus(this)
.times(pos)
.plus(this)
}
}
})
SVG.Element = SVG.invent({
// Initialize node
create: function(node) {
// make stroke value accessible dynamically
this._stroke = SVG.defaults.attrs.stroke
this._event = null
// initialize data object
this.dom = {}
// create circular reference
if (this.node = node) {
this.type = node.nodeName
this.node.instance = this
// store current attribute value
this._stroke = node.getAttribute('stroke') || this._stroke
}
}
// Add class methods
, extend: {
// Move over x-axis
x: function(x) {
return this.attr('x', x)
}
// Move over y-axis
, y: function(y) {
return this.attr('y', y)
}
// Move by center over x-axis
, cx: function(x) {
return x == null ? this.x() + this.width() / 2 : this.x(x - this.width() / 2)
}
// Move by center over y-axis
, cy: function(y) {
return y == null ? this.y() + this.height() / 2 : this.y(y - this.height() / 2)
}
// Move element to given x and y values
, move: function(x, y) {
return this.x(x).y(y)
}
// Move element by its center
, center: function(x, y) {
return this.cx(x).cy(y)
}
// Set width of element
, width: function(width) {
return this.attr('width', width)
}
// Set height of element
, height: function(height) {
return this.attr('height', height)
}
// Set element size to given width and height
, size: function(width, height) {
var p = proportionalSize(this, width, height)
return this
.width(new SVG.Number(p.width))
.height(new SVG.Number(p.height))
}
// Clone element
, clone: function(parent, withData) {
// write dom data to the dom so the clone can pickup the data
this.writeDataToDom()
// clone element and assign new id
var clone = assignNewId(this.node.cloneNode(true))
// insert the clone in the given parent or after myself
if(parent) parent.add(clone)
else this.after(clone)
return clone
}
// Remove element
, remove: function() {
if (this.parent())
this.parent().removeElement(this)
return this
}
// Replace element
, replace: function(element) {
this.after(element).remove()
return element
}
// Add element to given container and return self
, addTo: function(parent) {
return parent.put(this)
}
// Add element to given container and return container
, putIn: function(parent) {
return parent.add(this)
}
// Get / set id
, id: function(id) {
return this.attr('id', id)
}
// Checks whether the given point inside the bounding box of the element
, inside: function(x, y) {
var box = this.bbox()
return x > box.x
&& y > box.y
&& x < box.x + box.width
&& y < box.y + box.height
}
// Show element
, show: function() {
return this.style('display', '')
}
// Hide element
, hide: function() {
return this.style('display', 'none')
}
// Is element visible?
, visible: function() {
return this.style('display') != 'none'
}
// Return id on string conversion
, toString: function() {
return this.attr('id')
}
// Return array of classes on the node
, classes: function() {
var attr = this.attr('class')
return attr == null ? [] : attr.trim().split(SVG.regex.delimiter)
}
// Return true if class exists on the node, false otherwise
, hasClass: function(name) {
return this.classes().indexOf(name) != -1
}
// Add class to the node
, addClass: function(name) {
if (!this.hasClass(name)) {
var array = this.classes()
array.push(name)
this.attr('class', array.join(' '))
}
return this
}
// Remove class from the node
, removeClass: function(name) {
if (this.hasClass(name)) {
this.attr('class', this.classes().filter(function(c) {
return c != name
}).join(' '))
}
return this
}
// Toggle the presence of a class on the node
, toggleClass: function(name) {
return this.hasClass(name) ? this.removeClass(name) : this.addClass(name)
}
// Get referenced element form attribute value
, reference: function(attr) {
return SVG.get(this.attr(attr))
}
// Returns the parent element instance
, parent: function(type) {
var parent = this
// check for parent
if(!parent.node.parentNode) return null
// get parent element
parent = SVG.adopt(parent.node.parentNode)
if(!type) return parent
// loop trough ancestors if type is given
while(parent && parent.node instanceof window.SVGElement){
if(typeof type === 'string' ? parent.matches(type) : parent instanceof type) return parent
parent = SVG.adopt(parent.node.parentNode)
}
}
// Get parent document
, doc: function() {
return this instanceof SVG.Doc ? this : this.parent(SVG.Doc)
}
// return array of all ancestors of given type up to the root svg
, parents: function(type) {
var parents = [], parent = this
do{
parent = parent.parent(type)
if(!parent || !parent.node) break
parents.push(parent)
} while(parent.parent)
return parents
}
// matches the element vs a css selector
, matches: function(selector){
return matches(this.node, selector)
}
// Returns the svg node to call native svg methods on it
, native: function() {
return this.node
}
// Import raw svg
, svg: function(svg) {
// create temporary holder
var well = document.createElement('svg')
// act as a setter if svg is given
if (svg && this instanceof SVG.Parent) {
// dump raw svg
well.innerHTML = '<svg>' + svg.replace(/\n/, '').replace(/<(\w+)([^<]+?)\/>/g, '<$1$2></$1>') + '</svg>'
// transplant nodes
for (var i = 0, il = well.firstChild.childNodes.length; i < il; i++)
this.node.appendChild(well.firstChild.firstChild)
// otherwise act as a getter
} else {
// create a wrapping svg element in case of partial content
well.appendChild(svg = document.createElement('svg'))
// write svgjs data to the dom
this.writeDataToDom()
// insert a copy of this node
svg.appendChild(this.node.cloneNode(true))
// return target element
return well.innerHTML.replace(/^<svg>/, '').replace(/<\/svg>$/, '')
}
return this
}
// write svgjs data to the dom
, writeDataToDom: function() {
// dump variables recursively
if(this.each || this.lines){
var fn = this.each ? this : this.lines();
fn.each(function(){
this.writeDataToDom()
})
}
// remove previously set data
this.node.removeAttribute('svgjs:data')
if(Object.keys(this.dom).length)
this.node.setAttribute('svgjs:data', JSON.stringify(this.dom)) // see #428
return this
}
// set given data to the elements data property
, setData: function(o){
this.dom = o
return this
}
, is: function(obj){
return is(this, obj)
}
}
})
SVG.easing = {
'-': function(pos){return pos}
, '<>':function(pos){return -Math.cos(pos * Math.PI) / 2 + 0.5}
, '>': function(pos){return Math.sin(pos * Math.PI / 2)}
, '<': function(pos){return -Math.cos(pos * Math.PI / 2) + 1}
}
SVG.morph = function(pos){
return function(from, to) {
return new SVG.MorphObj(from, to).at(pos)
}
}
SVG.Situation = SVG.invent({
create: function(o){
this.init = false
this.reversed = false
this.reversing = false
this.duration = new SVG.Number(o.duration).valueOf()
this.delay = new SVG.Number(o.delay).valueOf()
this.start = +new Date() + this.delay
this.finish = this.start + this.duration
this.ease = o.ease
// this.loop is incremented from 0 to this.loops
// it is also incremented when in an infinite loop (when this.loops is true)
this.loop = 0
this.loops = false
this.animations = {
// functionToCall: [list of morphable objects]
// e.g. move: [SVG.Number, SVG.Number]
}
this.attrs = {
// holds all attributes which are not represented from a function svg.js provides
// e.g. someAttr: SVG.Number
}
this.styles = {
// holds all styles which should be animated
// e.g. fill-color: SVG.Color
}
this.transforms = [
// holds all transformations as transformation objects
// e.g. [SVG.Rotate, SVG.Translate, SVG.Matrix]
]
this.once = {
// functions to fire at a specific position
// e.g. "0.5": function foo(){}
}
}
})
SVG.FX = SVG.invent({
create: function(element) {
this._target = element
this.situations = []
this.active = false
this.situation = null
this.paused = false
this.lastPos = 0
this.pos = 0
// The absolute position of an animation is its position in the context of its complete duration (including delay and loops)
// When performing a delay, absPos is below 0 and when performing a loop, its value is above 1
this.absPos = 0
this._speed = 1
}
, extend: {
/**
* sets or returns the target of this animation
* @param o object || number In case of Object it holds all parameters. In case of number its the duration of the animation
* @param ease function || string Function which should be used for easing or easing keyword
* @param delay Number indicating the delay before the animation starts
* @return target || this
*/
animate: function(o, ease, delay){
if(typeof o == 'object'){
ease = o.ease
delay = o.delay
o = o.duration
}
var situation = new SVG.Situation({
duration: o || 1000,
delay: delay || 0,
ease: SVG.easing[ease || '-'] || ease
})
this.queue(situation)
return this
}
/**
* sets a delay before the next element of the queue is called
* @param delay Duration of delay in milliseconds
* @return this.target()
*/
, delay: function(delay){
// The delay is performed by an empty situation with its duration
// attribute set to the duration of the delay
var situation = new SVG.Situation({
duration: delay,
delay: 0,
ease: SVG.easing['-']
})
return this.queue(situation)
}
/**
* sets or returns the target of this animation
* @param null || target SVG.Element which should be set as new target
* @return target || this
*/
, target: function(target){
if(target && target instanceof SVG.Element){
this._target = target
return this
}
return this._target
}
// returns the absolute position at a given time
, timeToAbsPos: function(timestamp){
return (timestamp - this.situation.start) / (this.situation.duration/this._speed)
}
// returns the timestamp from a given absolute positon
, absPosToTime: function(absPos){
return this.situation.duration/this._speed * absPos + this.situation.start
}
// starts the animationloop
, startAnimFrame: function(){
this.stopAnimFrame()
this.animationFrame = window.requestAnimationFrame(function(){ this.step() }.bind(this))
}
// cancels the animationframe
, stopAnimFrame: function(){
window.cancelAnimationFrame(this.animationFrame)
}
// kicks off the animation - only does something when the queue is currently not active and at least one situation is set
, start: function(){
// dont start if already started
if(!this.active && this.situation){
this.active = true
this.startCurrent()
}
return this
}
// start the current situation
, startCurrent: function(){
this.situation.start = +new Date + this.situation.delay/this._speed
this.situation.finish = this.situation.start + this.situation.duration/this._speed
return this.initAnimations().step()
}
/**
* adds a function / Situation to the animation queue
* @param fn function / situation to add
* @return this
*/
, queue: function(fn){
if(typeof fn == 'function' || fn instanceof SVG.Situation)
this.situations.push(fn)
if(!this.situation) this.situation = this.situations.shift()
return this
}
/**
* pulls next element from the queue and execute it
* @return this
*/
, dequeue: function(){
// stop current animation
this.stop()
// get next animation from queue
this.situation = this.situations.shift()
if(this.situation){
if(this.situation instanceof SVG.Situation) {
this.start()
} else {
// If it is not a SVG.Situation, then it is a function, we execute it
this.situation.call(this)
}
}
return this
}
// updates all animations to the current state of the element
// this is important when one property could be changed from another property
, initAnimations: function() {
var i, source
var s = this.situation
if(s.init) return this
for(i in s.animations){
source = this.target()[i]()
// The condition is because some methods return a normal number instead
// of a SVG.Number
if(s.animations[i] instanceof SVG.Number)
source = new SVG.Number(source)
s.animations[i] = source.morph(s.animations[i])
}
for(i in s.attrs){
s.attrs[i] = new SVG.MorphObj(this.target().attr(i), s.attrs[i])
}
for(i in s.styles){
s.styles[i] = new SVG.MorphObj(this.target().style(i), s.styles[i])
}
s.initialTransformation = this.target().matrixify()
s.init = true
return this
}
, clearQueue: function(){
this.situations = []
return this
}
, clearCurrent: function(){
this.situation = null
return this
}
/** stops the animation immediately
* @param jumpToEnd A Boolean indicating whether to complete the current animation immediately.
* @param clearQueue A Boolean indicating whether to remove queued animation as well.
* @return this
*/
, stop: function(jumpToEnd, clearQueue){
var active = this.active
this.active = false
if(clearQueue){
this.clearQueue()
}
if(jumpToEnd && this.situation){
// initialize the situation if it was not
!active && this.startCurrent()
this.atEnd()
}
this.stopAnimFrame()
return this.clearCurrent()
}
/** resets the element to the state where the current element has started
* @return this
*/
, reset: function(){
if(this.situation){
var temp = this.situation
this.stop()
this.situation = temp
this.atStart()
}
return this
}
// Stop the currently-running animation, remove all queued animations, and complete all animations for the element.
, finish: function(){
this.stop(true, false)
while(this.dequeue().situation && this.stop(true, false));
this.clearQueue().clearCurrent()
return this
}
// set the internal animation pointer at the start position, before any loops, and updates the visualisation
, atStart: function() {
return this.at(0, true)
}
// set the internal animation pointer at the end position, after all the loops, and updates the visualisation
, atEnd: function() {
if (this.situation.loops === true) {
// If in a infinite loop, we end the current iteration
this.situation.loops = this.situation.loop + 1
}
if(typeof this.situation.loops == 'number') {
// If performing a finite number of loops, we go after all the loops
return this.at(this.situation.loops, true)
} else {
// If no loops, we just go at the end
return this.at(1, true)
}
}
// set the internal animation pointer to the specified position and updates the visualisation
// if isAbsPos is true, pos is treated as an absolute position
, at: function(pos, isAbsPos){
var durDivSpd = this.situation.duration/this._speed
this.absPos = pos
// If pos is not an absolute position, we convert it into one
if (!isAbsPos) {
if (this.situation.reversed) this.absPos = 1 - this.absPos
this.absPos += this.situation.loop
}
this.situation.start = +new Date - this.absPos * durDivSpd
this.situation.finish = this.situation.start + durDivSpd
return this.step(true)
}
/**
* sets or returns the speed of the animations
* @param speed null || Number The new speed of the animations
* @return Number || this
*/
, speed: function(speed){
if (speed === 0) return this.pause()
if (speed) {
this._speed = speed
// We use an absolute position here so that speed can affect the delay before the animation
return this.at(this.absPos, true)
} else return this._speed
}
// Make loopable
, loop: function(times, reverse) {
var c = this.last()
// store total loops
c.loops = (times != null) ? times : true
c.loop = 0
if(reverse) c.reversing = true
return this
}
// pauses the animation
, pause: function(){
this.paused = true
this.stopAnimFrame()
return this
}
// unpause the animation
, play: function(){
if(!this.paused) return this
this.paused = false
// We use an absolute position here so that the delay before the animation can be paused
return this.at(this.absPos, true)
}
/**
* toggle or set the direction of the animation
* true sets direction to backwards while false sets it to forwards
* @param reversed Boolean indicating whether to reverse the animation or not (default: toggle the reverse status)
* @return this
*/
, reverse: function(reversed){
var c = this.last()
if(typeof reversed == 'undefined') c.reversed = !c.reversed
else c.reversed = reversed
return this
}
/**
* returns a float from 0-1 indicating the progress of the current animation
* @param eased Boolean indicating whether the returned position should be eased or not
* @return number
*/
, progress: function(easeIt){
return easeIt ? this.situation.ease(this.pos) : this.pos
}
/**
* adds a callback function which is called when the current animation is finished
* @param fn Function which should be executed as callback
* @return number
*/
, after: function(fn){
var c = this.last()
, wrapper = function wrapper(e){
if(e.detail.situation == c){
fn.call(this, c)
this.off('finished.fx', wrapper) // prevent memory leak
}
}
this.target().on('finished.fx', wrapper)
return this._callStart()
}
// adds a callback which is called whenever one animation step is performed
, during: function(fn){
var c = this.last()
, wrapper = function(e){
if(e.detail.situation == c){
fn.call(this, e.detail.pos, SVG.morph(e.detail.pos), e.detail.eased, c)
}
}
// see above
this.target().off('during.fx', wrapper).on('during.fx', wrapper)
this.after(function(){
this.off('during.fx', wrapper)
})
return this._callStart()
}
// calls after ALL animations in the queue are finished
, afterAll: function(fn){
var wrapper = function wrapper(e){
fn.call(this)
this.off('allfinished.fx', wrapper)
}
// see above
this.target().off('allfinished.fx', wrapper).on('allfinished.fx', wrapper)
return this._callStart()
}
// calls on every animation step for all animations
, duringAll: function(fn){
var wrapper = function(e){
fn.call(this, e.detail.pos, SVG.morph(e.detail.pos), e.detail.eased, e.detail.situation)
}
this.target().off('during.fx', wrapper).on('during.fx', wrapper)
this.afterAll(function(){
this.off('during.fx', wrapper)
})
return this._callStart()
}
, last: function(){
return this.situations.length ? this.situations[this.situations.length-1] : this.situation
}
// adds one property to the animations
, add: function(method, args, type){
this.last()[type || 'animations'][method] = args
return this._callStart()
}
/** perform one step of the animation
* @param ignoreTime Boolean indicating whether to ignore time and use position directly or recalculate position based on time
* @return this
*/
, step: function(ignoreTime){
// convert current time to an absolute position
if(!ignoreTime) this.absPos = this.timeToAbsPos(+new Date)
// This part convert an absolute position to a position
if(this.situation.loops !== false) {
var absPos, absPosInt, lastLoop
// If the absolute position is below 0, we just treat it as if it was 0
absPos = Math.max(this.absPos, 0)
absPosInt = Math.floor(absPos)
if(this.situation.loops === true || absPosInt < this.situation.loops) {
this.pos = absPos - absPosInt
lastLoop = this.situation.loop
this.situation.loop = absPosInt
} else {
this.absPos = this.situation.loops
this.pos = 1
// The -1 here is because we don't want to toggle reversed when all the loops have been completed
lastLoop = this.situation.loop - 1
this.situation.loop = this.situation.loops
}
if(this.situation.reversing) {
// Toggle reversed if an odd number of loops as occured since the last call of step
this.situation.reversed = this.situation.reversed != Boolean((this.situation.loop - lastLoop) % 2)
}
} else {
// If there are no loop, the absolute position must not be above 1
this.absPos = Math.min(this.absPos, 1)
this.pos = this.absPos
}
// while the absolute position can be below 0, the position must not be below 0
if(this.pos < 0) this.pos = 0
if(this.situation.reversed) this.pos = 1 - this.pos
// apply easing
var eased = this.situation.ease(this.pos)
// call once-callbacks
for(var i in this.situation.once){
if(i > this.lastPos && i <= eased){
this.situation.once[i].call(this.target(), this.pos, eased)
delete this.situation.once[i]
}
}
// fire during callback with position, eased position and current situation as parameter
if(this.active) this.target().fire('during', {pos: this.pos, eased: eased, fx: this, situation: this.situation})
// the user may call stop or finish in the during callback
// so make sure that we still have a valid situation
if(!this.situation){
return this
}
// apply the actual animation to every property
this.eachAt()
// do final code when situation is finished
if((this.pos == 1 && !this.situation.reversed) || (this.situation.reversed && this.pos == 0)){
// stop animation callback
this.stopAnimFrame()
// fire finished callback with current situation as parameter
this.target().fire('finished', {fx:this, situation: this.situation})
if(!this.situations.length){
this.target().fire('allfinished')
this.target().off('.fx') // there shouldnt be any binding left, but to make sure...
this.active = false
}
// start next animation
if(this.active) this.dequeue()
else this.clearCurrent()
}else if(!this.paused && this.active){
// we continue animating when we are not at the end
this.startAnimFrame()
}
// save last eased position for once callback triggering
this.lastPos = eased
return this
}
// calculates the step for every property and calls block with it
, eachAt: function(){
var i, len, at, self = this, target = this.target(), s = this.situation
// apply animations which can be called trough a method
for(i in s.animations){
at = [].concat(s.animations[i]).map(function(el){
return typeof el !== 'string' && el.at ? el.at(s.ease(self.pos), self.pos) : el
})
target[i].apply(target, at)
}
// apply animation which has to be applied with attr()
for(i in s.attrs){
at = [i].concat(s.attrs[i]).map(function(el){
return typeof el !== 'string' && el.at ? el.at(s.ease(self.pos), self.pos) : el
})
target.attr.apply(target, at)
}
// apply animation which has to be applied with style()
for(i in s.styles){
at = [i].concat(s.styles[i]).map(function(el){
return typeof el !== 'string' && el.at ? el.at(s.ease(self.pos), self.pos) : el
})
target.style.apply(target, at)
}
// animate initialTransformation which has to be chained
if(s.transforms.length){
// get initial initialTransformation
at = s.initialTransformation
for(i = 0, len = s.transforms.length; i < len; i++){
// get next transformation in chain
var a = s.transforms[i]
// multiply matrix directly
if(a instanceof SVG.Matrix){
if(a.relative){
at = at.multiply(new SVG.Matrix().morph(a).at(s.ease(this.pos)))
}else{
at = at.morph(a).at(s.ease(this.pos))
}
continue
}
// when transformation is absolute we have to reset the needed transformation first
if(!a.relative)
a.undo(at.extract())
// and reapply it after
at = at.multiply(a.at(s.ease(this.pos)))
}
// set new matrix on element
target.matrix(at)
}
return this
}
// adds an once-callback which is called at a specific position and never again
, once: function(pos, fn, isEased){
if(!isEased)pos = this.situation.ease(pos)
this.situation.once[pos] = fn
return this
}
, _callStart: function() {
setTimeout(function(){this.start()}.bind(this), 0)
return this
}
}
, parent: SVG.Element
// Add method to parent elements
, construct: {
// Get fx module or create a new one, then animate with given duration and ease
animate: function(o, ease, delay) {
return (this.fx || (this.fx = new SVG.FX(this))).animate(o, ease, delay)
}
, delay: function(delay){
return (this.fx || (this.fx = new SVG.FX(this))).delay(delay)
}
, stop: function(jumpToEnd, clearQueue) {
if (this.fx)
this.fx.stop(jumpToEnd, clearQueue)
return this
}
, finish: function() {
if (this.fx)
this.fx.finish()
return this
}
// Pause current animation
, pause: function() {
if (this.fx)
this.fx.pause()
return this
}
// Play paused current animation
, play: function() {
if (this.fx)
this.fx.play()
return this
}
// Set/Get the speed of the animations
, speed: function(speed) {
if (this.fx)
if (speed == null)
return this.fx.speed()
else
this.fx.speed(speed)
return this
}
}
})
// MorphObj is used whenever no morphable object is given
SVG.MorphObj = SVG.invent({
create: function(from, to){
// prepare color for morphing
if(SVG.Color.isColor(to)) return new SVG.Color(from).morph(to)
// prepare number for morphing
if(SVG.regex.numberAndUnit.test(to)) return new SVG.Number(from).morph(to)
// prepare for plain morphing
this.value = from
this.destination = to
}
, extend: {
at: function(pos, real){
return real < 1 ? this.value : this.destination
},
valueOf: function(){
return this.value
}
}
})
SVG.extend(SVG.FX, {
// Add animatable attributes
attr: function(a, v, relative) {
// apply attributes individually
if (typeof a == 'object') {
for (var key in a)
this.attr(key, a[key])
} else {
this.add(a, v, 'attrs')
}
return this
}
// Add animatable styles
, style: function(s, v) {
if (typeof s == 'object')
for (var key in s)
this.style(key, s[key])
else
this.add(s, v, 'styles')
return this
}
// Animatable x-axis
, x: function(x, relative) {
if(this.target() instanceof SVG.G){
this.transform({x:x}, relative)
return this
}
var num = new SVG.Number(x)
num.relative = relative
return this.add('x', num)
}
// Animatable y-axis
, y: function(y, relative) {
if(this.target() instanceof SVG.G){
this.transform({y:y}, relative)
return this
}
var num = new SVG.Number(y)
num.relative = relative
return this.add('y', num)
}
// Animatable center x-axis
, cx: function(x) {
return this.add('cx', new SVG.Number(x))
}
// Animatable center y-axis
, cy: function(y) {
return this.add('cy', new SVG.Number(y))
}
// Add animatable move
, move: function(x, y) {
return this.x(x).y(y)
}
// Add animatable center
, center: function(x, y) {
return this.cx(x).cy(y)
}
// Add animatable size
, size: function(width, height) {
if (this.target() instanceof SVG.Text) {
// animate font size for Text elements
this.attr('font-size', width)
} else {
// animate bbox based size for all other elements
var box
if(!width || !height){
box = this.target().bbox()
}
if(!width){
width = box.width / box.height * height
}
if(!height){
height = box.height / box.width * width
}
this.add('width' , new SVG.Number(width))
.add('height', new SVG.Number(height))
}
return this
}
// Add animatable plot
, plot: function() {
// We use arguments here since SVG.Line's plot method can be passed 4 parameters
return this.add('plot', arguments.length > 1 ? [].slice.call(arguments) : arguments[0])
}
// Add leading method
, leading: function(value) {
return this.target().leading ?
this.add('leading', new SVG.Number(value)) :
this
}
// Add animatable viewbox
, viewbox: function(x, y, width, height) {
if (this.target() instanceof SVG.Container) {
this.add('viewbox', new SVG.ViewBox(x, y, width, height))
}
return this
}
, update: function(o) {
if (this.target() instanceof SVG.Stop) {
if (typeof o == 'number' || o instanceof SVG.Number) {
return this.update({
offset: arguments[0]
, color: arguments[1]
, opacity: arguments[2]
})
}
if (o.opacity != null) this.attr('stop-opacity', o.opacity)
if (o.color != null) this.attr('stop-color', o.color)
if (o.offset != null) this.attr('offset', o.offset)
}
return this
}
})
SVG.Box = SVG.invent({
create: function(x, y, width, height) {
if (typeof x == 'object' && !(x instanceof SVG.Element)) {
// chromes getBoundingClientRect has no x and y property
return SVG.Box.call(this, x.left != null ? x.left : x.x , x.top != null ? x.top : x.y, x.width, x.height)
} else if (arguments.length == 4) {
this.x = x
this.y = y
this.width = width
this.height = height
}
// add center, right, bottom...
fullBox(this)
}
, extend: {
// Merge rect box with another, return a new instance
merge: function(box) {
var b = new this.constructor()
// merge boxes
b.x = Math.min(this.x, box.x)
b.y = Math.min(this.y, box.y)
b.width = Math.max(this.x + this.width, box.x + box.width) - b.x
b.height = Math.max(this.y + this.height, box.y + box.height) - b.y
return fullBox(b)
}
, transform: function(m) {
var xMin = Infinity, xMax = -Infinity, yMin = Infinity, yMax = -Infinity, p, bbox
var pts = [
new SVG.Point(this.x, this.y),
new SVG.Point(this.x2, this.y),
new SVG.Point(this.x, this.y2),
new SVG.Point(this.x2, this.y2)
]
pts.forEach(function(p) {
p = p.transform(m)
xMin = Math.min(xMin,p.x)
xMax = Math.max(xMax,p.x)
yMin = Math.min(yMin,p.y)
yMax = Math.max(yMax,p.y)
})
bbox = new this.constructor()
bbox.x = xMin
bbox.width = xMax-xMin
bbox.y = yMin
bbox.height = yMax-yMin
fullBox(bbox)
return bbox
}
}
})
SVG.BBox = SVG.invent({
// Initialize
create: function(element) {
SVG.Box.apply(this, [].slice.call(arguments))
// get values if element is given
if (element instanceof SVG.Element) {
var box
// yes this is ugly, but Firefox can be a bitch when it comes to elements that are not yet rendered
try {
if (!document.documentElement.contains){
// This is IE - it does not support contains() for top-level SVGs
var topParent = element.node
while (topParent.parentNode){
topParent = topParent.parentNode
}
if (topParent != document) throw new Exception('Element not in the dom')
} else {
// the element is NOT in the dom, throw error
if(!document.documentElement.contains(element.node)) throw new Exception('Element not in the dom')
}
// find native bbox
box = element.node.getBBox()
} catch(e) {
if(element instanceof SVG.Shape){
var clone = element.clone(SVG.parser.draw.instance).show()
box = clone.node.getBBox()
clone.remove()
}else{
box = {
x: element.node.clientLeft
, y: element.node.clientTop
, width: element.node.clientWidth
, height: element.node.clientHeight
}
}
}
SVG.Box.call(this, box)
}
}
// Define ancestor
, inherit: SVG.Box
// Define Parent
, parent: SVG.Element
// Constructor
, construct: {
// Get bounding box
bbox: function() {
return new SVG.BBox(this)
}
}
})
SVG.BBox.prototype.constructor = SVG.BBox
SVG.extend(SVG.Element, {
tbox: function(){
console.warn('Use of TBox is deprecated and mapped to RBox. Use .rbox() instead.')
return this.rbox(this.doc())
}
})
SVG.RBox = SVG.invent({
// Initialize
create: function(element) {
SVG.Box.apply(this, [].slice.call(arguments))
if (element instanceof SVG.Element) {
SVG.Box.call(this, element.node.getBoundingClientRect())
}
}
, inherit: SVG.Box
// define Parent
, parent: SVG.Element
, extend: {
addOffset: function() {
// offset by window scroll position, because getBoundingClientRect changes when window is scrolled
this.x += window.pageXOffset
this.y += window.pageYOffset
return this
}
}
// Constructor
, construct: {
// Get rect box
rbox: function(el) {
if (el) return new SVG.RBox(this).transform(el.screenCTM().inverse())
return new SVG.RBox(this).addOffset()
}
}
})
SVG.RBox.prototype.constructor = SVG.RBox
SVG.Matrix = SVG.invent({
// Initialize
create: function(source) {
var i, base = arrayToMatrix([1, 0, 0, 1, 0, 0])
// ensure source as object
source = source instanceof SVG.Element ?
source.matrixify() :
typeof source === 'string' ?
arrayToMatrix(source.split(SVG.regex.delimiter).map(parseFloat)) :
arguments.length == 6 ?
arrayToMatrix([].slice.call(arguments)) :
Array.isArray(source) ?
arrayToMatrix(source) :
typeof source === 'object' ?
source : base
// merge source
for (i = abcdef.length - 1; i >= 0; --i)
this[abcdef[i]] = source && typeof source[abcdef[i]] === 'number' ?
source[abcdef[i]] : base[abcdef[i]]
}
// Add methods
, extend: {
// Extract individual transformations
extract: function() {
// find delta transform points
var px = deltaTransformPoint(this, 0, 1)
, py = deltaTransformPoint(this, 1, 0)
, skewX = 180 / Math.PI * Math.atan2(px.y, px.x) - 90
return {
// translation
x: this.e
, y: this.f
, transformedX:(this.e * Math.cos(skewX * Math.PI / 180) + this.f * Math.sin(skewX * Math.PI / 180)) / Math.sqrt(this.a * this.a + this.b * this.b)
, transformedY:(this.f * Math.cos(skewX * Math.PI / 180) + this.e * Math.sin(-skewX * Math.PI / 180)) / Math.sqrt(this.c * this.c + this.d * this.d)
// skew
, skewX: -skewX
, skewY: 180 / Math.PI * Math.atan2(py.y, py.x)
// scale
, scaleX: Math.sqrt(this.a * this.a + this.b * this.b)
, scaleY: Math.sqrt(this.c * this.c + this.d * this.d)
// rotation
, rotation: skewX
, a: this.a
, b: this.b
, c: this.c
, d: this.d
, e: this.e
, f: this.f
, matrix: new SVG.Matrix(this)
}
}
// Clone matrix
, clone: function() {
return new SVG.Matrix(this)
}
// Morph one matrix into another
, morph: function(matrix) {
// store new destination
this.destination = new SVG.Matrix(matrix)
return this
}
// Get morphed matrix at a given position
, at: function(pos) {
// make sure a destination is defined
if (!this.destination) return this
// calculate morphed matrix at a given position
var matrix = new SVG.Matrix({
a: this.a + (this.destination.a - this.a) * pos
, b: this.b + (this.destination.b - this.b) * pos
, c: this.c + (this.destination.c - this.c) * pos
, d: this.d + (this.destination.d - this.d) * pos
, e: this.e + (this.destination.e - this.e) * pos
, f: this.f + (this.destination.f - this.f) * pos
})
return matrix
}
// Multiplies by given matrix
, multiply: function(matrix) {
return new SVG.Matrix(this.native().multiply(parseMatrix(matrix).native()))
}
// Inverses matrix
, inverse: function() {
return new SVG.Matrix(this.native().inverse())
}
// Translate matrix
, translate: function(x, y) {
return new SVG.Matrix(this.native().translate(x || 0, y || 0))
}
// Scale matrix
, scale: function(x, y, cx, cy) {
// support uniformal scale
if (arguments.length == 1) {
y = x
} else if (arguments.length == 3) {
cy = cx
cx = y
y = x
}
return this.around(cx, cy, new SVG.Matrix(x, 0, 0, y, 0, 0))
}
// Rotate matrix
, rotate: function(r, cx, cy) {
// convert degrees to radians
r = SVG.utils.radians(r)
return this.around(cx, cy, new SVG.Matrix(Math.cos(r), Math.sin(r), -Math.sin(r), Math.cos(r), 0, 0))
}
// Flip matrix on x or y, at a given offset
, flip: function(a, o) {
return a == 'x' ?
this.scale(-1, 1, o, 0) :
a == 'y' ?
this.scale(1, -1, 0, o) :
this.scale(-1, -1, a, o != null ? o : a)
}
// Skew
, skew: function(x, y, cx, cy) {
// support uniformal skew
if (arguments.length == 1) {
y = x
} else if (arguments.length == 3) {
cy = cx
cx = y
y = x
}
// convert degrees to radians
x = SVG.utils.radians(x)
y = SVG.utils.radians(y)
return this.around(cx, cy, new SVG.Matrix(1, Math.tan(y), Math.tan(x), 1, 0, 0))
}
// SkewX
, skewX: function(x, cx, cy) {
return this.skew(x, 0, cx, cy)
}
// SkewY
, skewY: function(y, cx, cy) {
return this.skew(0, y, cx, cy)
}
// Transform around a center point
, around: function(cx, cy, matrix) {
return this
.multiply(new SVG.Matrix(1, 0, 0, 1, cx || 0, cy || 0))
.multiply(matrix)
.multiply(new SVG.Matrix(1, 0, 0, 1, -cx || 0, -cy || 0))
}
// Convert to native SVGMatrix
, native: function() {
// create new matrix
var matrix = SVG.parser.native.createSVGMatrix()
// update with current values
for (var i = abcdef.length - 1; i >= 0; i--)
matrix[abcdef[i]] = this[abcdef[i]]
return matrix
}
// Convert matrix to string
, toString: function() {
return 'matrix(' + this.a + ',' + this.b + ',' + this.c + ',' + this.d + ',' + this.e + ',' + this.f + ')'
}
}
// Define parent
, parent: SVG.Element
// Add parent method
, construct: {
// Get current matrix
ctm: function() {
return new SVG.Matrix(this.node.getCTM())
},
// Get current screen matrix
screenCTM: function() {
/* https://bugzilla.mozilla.org/show_bug.cgi?id=1344537
This is needed because FF does not return the transformation matrix
for the inner coordinate system when getScreenCTM() is called on nested svgs.
However all other Browsers do that */
if(this instanceof SVG.Nested) {
var rect = this.rect(1,1)
var m = rect.node.getScreenCTM()
rect.remove()
return new SVG.Matrix(m)
}
return new SVG.Matrix(this.node.getScreenCTM())
}
}
})
SVG.Point = SVG.invent({
// Initialize
create: function(x,y) {
var i, source, base = {x:0, y:0}
// ensure source as object
source = Array.isArray(x) ?
{x:x[0], y:x[1]} :
typeof x === 'object' ?
{x:x.x, y:x.y} :
x != null ?
{x:x, y:(y != null ? y : x)} : base // If y has no value, then x is used has its value
// merge source
this.x = source.x
this.y = source.y
}
// Add methods
, extend: {
// Clone point
clone: function() {
return new SVG.Point(this)
}
// Morph one point into another
, morph: function(x, y) {
// store new destination
this.destination = new SVG.Point(x, y)
return this
}
// Get morphed point at a given position
, at: function(pos) {
// make sure a destination is defined
if (!this.destination) return this
// calculate morphed matrix at a given position
var point = new SVG.Point({
x: this.x + (this.destination.x - this.x) * pos
, y: this.y + (this.destination.y - this.y) * pos
})
return point
}
// Convert to native SVGPoint
, native: function() {
// create new point
var point = SVG.parser.native.createSVGPoint()
// update with current values
point.x = this.x
point.y = this.y
return point
}
// transform point with matrix
, transform: function(matrix) {
return new SVG.Point(this.native().matrixTransform(matrix.native()))
}
}
})
SVG.extend(SVG.Element, {
// Get point
point: function(x, y) {
return new SVG.Point(x,y).transform(this.screenCTM().inverse());
}
})
SVG.extend(SVG.Element, {
// Set svg element attribute
attr: function(a, v, n) {
// act as full getter
if (a == null) {
// get an object of attributes
a = {}
v = this.node.attributes
for (n = v.length - 1; n >= 0; n--)
a[v[n].nodeName] = SVG.regex.isNumber.test(v[n].nodeValue) ? parseFloat(v[n].nodeValue) : v[n].nodeValue
return a
} else if (typeof a == 'object') {
// apply every attribute individually if an object is passed
for (v in a) this.attr(v, a[v])
} else if (v === null) {
// remove value
this.node.removeAttribute(a)
} else if (v == null) {
// act as a getter if the first and only argument is not an object
v = this.node.getAttribute(a)
return v == null ?
SVG.defaults.attrs[a] :
SVG.regex.isNumber.test(v) ?
parseFloat(v) : v
} else {
// BUG FIX: some browsers will render a stroke if a color is given even though stroke width is 0
if (a == 'stroke-width')
this.attr('stroke', parseFloat(v) > 0 ? this._stroke : null)
else if (a == 'stroke')
this._stroke = v
// convert image fill and stroke to patterns
if (a == 'fill' || a == 'stroke') {
if (SVG.regex.isImage.test(v))
v = this.doc().defs().image(v, 0, 0)
if (v instanceof SVG.Image)
v = this.doc().defs().pattern(0, 0, function() {
this.add(v)
})
}
// ensure correct numeric values (also accepts NaN and Infinity)
if (typeof v === 'number')
v = new SVG.Number(v)
// ensure full hex color
else if (SVG.Color.isColor(v))
v = new SVG.Color(v)
// parse array values
else if (Array.isArray(v))
v = new SVG.Array(v)
// if the passed attribute is leading...
if (a == 'leading') {
// ... call the leading method instead
if (this.leading)
this.leading(v)
} else {
// set given attribute on node
typeof n === 'string' ?
this.node.setAttributeNS(n, a, v.toString()) :
this.node.setAttribute(a, v.toString())
}
// rebuild if required
if (this.rebuild && (a == 'font-size' || a == 'x'))
this.rebuild(a, v)
}
return this
}
})
SVG.extend(SVG.Element, {
// Add transformations
transform: function(o, relative) {
// get target in case of the fx module, otherwise reference this
var target = this
, matrix, bbox
// act as a getter
if (typeof o !== 'object') {
// get current matrix
matrix = new SVG.Matrix(target).extract()
return typeof o === 'string' ? matrix[o] : matrix
}
// get current matrix
matrix = new SVG.Matrix(target)
// ensure relative flag
relative = !!relative || !!o.relative
// act on matrix
if (o.a != null) {
matrix = relative ?
// relative
matrix.multiply(new SVG.Matrix(o)) :
// absolute
new SVG.Matrix(o)
// act on rotation
} else if (o.rotation != null) {
// ensure centre point
ensureCentre(o, target)
// apply transformation
matrix = relative ?
// relative
matrix.rotate(o.rotation, o.cx, o.cy) :
// absolute
matrix.rotate(o.rotation - matrix.extract().rotation, o.cx, o.cy)
// act on scale
} else if (o.scale != null || o.scaleX != null || o.scaleY != null) {
// ensure centre point
ensureCentre(o, target)
// ensure scale values on both axes
o.scaleX = o.scale != null ? o.scale : o.scaleX != null ? o.scaleX : 1
o.scaleY = o.scale != null ? o.scale : o.scaleY != null ? o.scaleY : 1
if (!relative) {
// absolute; multiply inversed values
var e = matrix.extract()
o.scaleX = o.scaleX * 1 / e.scaleX
o.scaleY = o.scaleY * 1 / e.scaleY
}
matrix = matrix.scale(o.scaleX, o.scaleY, o.cx, o.cy)
// act on skew
} else if (o.skew != null || o.skewX != null || o.skewY != null) {
// ensure centre point
ensureCentre(o, target)
// ensure skew values on both axes
o.skewX = o.skew != null ? o.skew : o.skewX != null ? o.skewX : 0
o.skewY = o.skew != null ? o.skew : o.skewY != null ? o.skewY : 0
if (!relative) {
// absolute; reset skew values
var e = matrix.extract()
matrix = matrix.multiply(new SVG.Matrix().skew(e.skewX, e.skewY, o.cx, o.cy).inverse())
}
matrix = matrix.skew(o.skewX, o.skewY, o.cx, o.cy)
// act on flip
} else if (o.flip) {
if(o.flip == 'x' || o.flip == 'y') {
o.offset = o.offset == null ? target.bbox()['c' + o.flip] : o.offset
} else {
if(o.offset == null) {
bbox = target.bbox()
o.flip = bbox.cx
o.offset = bbox.cy
} else {
o.flip = o.offset
}
}
matrix = new SVG.Matrix().flip(o.flip, o.offset)
// act on translate
} else if (o.x != null || o.y != null) {
if (relative) {
// relative
matrix = matrix.translate(o.x, o.y)
} else {
// absolute
if (o.x != null) matrix.e = o.x
if (o.y != null) matrix.f = o.y
}
}
return this.attr('transform', matrix)
}
})
SVG.extend(SVG.FX, {
transform: function(o, relative) {
// get target in case of the fx module, otherwise reference this
var target = this.target()
, matrix, bbox
// act as a getter
if (typeof o !== 'object') {
// get current matrix
matrix = new SVG.Matrix(target).extract()
return typeof o === 'string' ? matrix[o] : matrix
}
// ensure relative flag
relative = !!relative || !!o.relative
// act on matrix
if (o.a != null) {
matrix = new SVG.Matrix(o)
// act on rotation
} else if (o.rotation != null) {
// ensure centre point
ensureCentre(o, target)
// apply transformation
matrix = new SVG.Rotate(o.rotation, o.cx, o.cy)
// act on scale
} else if (o.scale != null || o.scaleX != null || o.scaleY != null) {
// ensure centre point
ensureCentre(o, target)
// ensure scale values on both axes
o.scaleX = o.scale != null ? o.scale : o.scaleX != null ? o.scaleX : 1
o.scaleY = o.scale != null ? o.scale : o.scaleY != null ? o.scaleY : 1
matrix = new SVG.Scale(o.scaleX, o.scaleY, o.cx, o.cy)
// act on skew
} else if (o.skewX != null || o.skewY != null) {
// ensure centre point
ensureCentre(o, target)
// ensure skew values on both axes
o.skewX = o.skewX != null ? o.skewX : 0
o.skewY = o.skewY != null ? o.skewY : 0
matrix = new SVG.Skew(o.skewX, o.skewY, o.cx, o.cy)
// act on flip
} else if (o.flip) {
if(o.flip == 'x' || o.flip == 'y') {
o.offset = o.offset == null ? target.bbox()['c' + o.flip] : o.offset
} else {
if(o.offset == null) {
bbox = target.bbox()
o.flip = bbox.cx
o.offset = bbox.cy
} else {
o.flip = o.offset
}
}
matrix = new SVG.Matrix().flip(o.flip, o.offset)
// act on translate
} else if (o.x != null || o.y != null) {
matrix = new SVG.Translate(o.x, o.y)
}
if(!matrix) return this
matrix.relative = relative
this.last().transforms.push(matrix)
return this._callStart()
}
})
SVG.extend(SVG.Element, {
// Reset all transformations
untransform: function() {
return this.attr('transform', null)
},
// merge the whole transformation chain into one matrix and returns it
matrixify: function() {
var matrix = (this.attr('transform') || '')
// split transformations
.split(SVG.regex.transforms).slice(0,-1).map(function(str){
// generate key => value pairs
var kv = str.trim().split('(')
return [kv[0], kv[1].split(SVG.regex.delimiter).map(function(str){ return parseFloat(str) })]
})
// merge every transformation into one matrix
.reduce(function(matrix, transform){
if(transform[0] == 'matrix') return matrix.multiply(arrayToMatrix(transform[1]))
return matrix[transform[0]].apply(matrix, transform[1])
}, new SVG.Matrix())
return matrix
},
// add an element to another parent without changing the visual representation on the screen
toParent: function(parent) {
if(this == parent) return this
var ctm = this.screenCTM()
var pCtm = parent.screenCTM().inverse()
this.addTo(parent).untransform().transform(pCtm.multiply(ctm))
return this
},
// same as above with parent equals root-svg
toDoc: function() {
return this.toParent(this.doc())
}
})
SVG.Transformation = SVG.invent({
create: function(source, inversed){
if(arguments.length > 1 && typeof inversed != 'boolean'){
return this.constructor.call(this, [].slice.call(arguments))
}
if(Array.isArray(source)){
for(var i = 0, len = this.arguments.length; i < len; ++i){
this[this.arguments[i]] = source[i]
}
} else if(typeof source == 'object'){
for(var i = 0, len = this.arguments.length; i < len; ++i){
this[this.arguments[i]] = source[this.arguments[i]]
}
}
this.inversed = false
if(inversed === true){
this.inversed = true
}
}
, extend: {
arguments: []
, method: ''
, at: function(pos){
var params = []
for(var i = 0, len = this.arguments.length; i < len; ++i){
params.push(this[this.arguments[i]])
}
var m = this._undo || new SVG.Matrix()
m = new SVG.Matrix().morph(SVG.Matrix.prototype[this.method].apply(m, params)).at(pos)
return this.inversed ? m.inverse() : m
}
, undo: function(o){
for(var i = 0, len = this.arguments.length; i < len; ++i){
o[this.arguments[i]] = typeof this[this.arguments[i]] == 'undefined' ? 0 : o[this.arguments[i]]
}
// The method SVG.Matrix.extract which was used before calling this
// method to obtain a value for the parameter o doesn't return a cx and
// a cy so we use the ones that were provided to this object at its creation
o.cx = this.cx
o.cy = this.cy
this._undo = new SVG[capitalize(this.method)](o, true).at(1)
return this
}
}
})
SVG.Translate = SVG.invent({
parent: SVG.Matrix
, inherit: SVG.Transformation
, create: function(source, inversed){
this.constructor.apply(this, [].slice.call(arguments))
}
, extend: {
arguments: ['transformedX', 'transformedY']
, method: 'translate'
}
})
SVG.Rotate = SVG.invent({
parent: SVG.Matrix
, inherit: SVG.Transformation
, create: function(source, inversed){
this.constructor.apply(this, [].slice.call(arguments))
}
, extend: {
arguments: ['rotation', 'cx', 'cy']
, method: 'rotate'
, at: function(pos){
var m = new SVG.Matrix().rotate(new SVG.Number().morph(this.rotation - (this._undo ? this._undo.rotation : 0)).at(pos), this.cx, this.cy)
return this.inversed ? m.inverse() : m
}
, undo: function(o){
this._undo = o
return this
}
}
})
SVG.Scale = SVG.invent({
parent: SVG.Matrix
, inherit: SVG.Transformation
, create: function(source, inversed){
this.constructor.apply(this, [].slice.call(arguments))
}
, extend: {
arguments: ['scaleX', 'scaleY', 'cx', 'cy']
, method: 'scale'
}
})
SVG.Skew = SVG.invent({
parent: SVG.Matrix
, inherit: SVG.Transformation
, create: function(source, inversed){
this.constructor.apply(this, [].slice.call(arguments))
}
, extend: {
arguments: ['skewX', 'skewY', 'cx', 'cy']
, method: 'skew'
}
})
SVG.extend(SVG.Element, {
// Dynamic style generator
style: function(s, v) {
if (arguments.length == 0) {
// get full style
return this.node.style.cssText || ''
} else if (arguments.length < 2) {
// apply every style individually if an object is passed
if (typeof s == 'object') {
for (v in s) this.style(v, s[v])
} else if (SVG.regex.isCss.test(s)) {
// parse css string
s = s.split(/\s*;\s*/)
// filter out suffix ; and stuff like ;;
.filter(function(e) { return !!e })
.map(function(e){ return e.split(/\s*:\s*/) })
// apply every definition individually
while (v = s.pop()) {
this.style(v[0], v[1])
}
} else {
// act as a getter if the first and only argument is not an object
return this.node.style[camelCase(s)]
}
} else {
this.node.style[camelCase(s)] = v === null || SVG.regex.isBlank.test(v) ? '' : v
}
return this
}
})
SVG.Parent = SVG.invent({
// Initialize node
create: function(element) {
this.constructor.call(this, element)
}
// Inherit from
, inherit: SVG.Element
// Add class methods
, extend: {
// Returns all child elements
children: function() {
return SVG.utils.map(SVG.utils.filterSVGElements(this.node.childNodes), function(node) {
return SVG.adopt(node)
})
}
// Add given element at a position
, add: function(element, i) {
if (i == null)
this.node.appendChild(element.node)
else if (element.node != this.node.childNodes[i])
this.node.insertBefore(element.node, this.node.childNodes[i])
return this
}
// Basically does the same as `add()` but returns the added element instead
, put: function(element, i) {
this.add(element, i)
return element
}
// Checks if the given element is a child
, has: function(element) {
return this.index(element) >= 0
}
// Gets index of given element
, index: function(element) {
return [].slice.call(this.node.childNodes).indexOf(element.node)
}
// Get a element at the given index
, get: function(i) {
return SVG.adopt(this.node.childNodes[i])
}
// Get first child
, first: function() {
return this.get(0)
}
// Get the last child
, last: function() {
return this.get(this.node.childNodes.length - 1)
}
// Iterates over all children and invokes a given block
, each: function(block, deep) {
var i, il
, children = this.children()
for (i = 0, il = children.length; i < il; i++) {
if (children[i] instanceof SVG.Element)
block.apply(children[i], [i, children])
if (deep && (children[i] instanceof SVG.Container))
children[i].each(block, deep)
}
return this
}
// Remove a given child
, removeElement: function(element) {
this.node.removeChild(element.node)
return this
}
// Remove all elements in this container
, clear: function() {
// remove children
while(this.node.hasChildNodes())
this.node.removeChild(this.node.lastChild)
// remove defs reference
delete this._defs
return this
}
, // Get defs
defs: function() {
return this.doc().defs()
}
}
})
SVG.extend(SVG.Parent, {
ungroup: function(parent, depth) {
if(depth === 0 || this instanceof SVG.Defs || this.node == SVG.parser.draw) return this
parent = parent || (this instanceof SVG.Doc ? this : this.parent(SVG.Parent))
depth = depth || Infinity
this.each(function(){
if(this instanceof SVG.Defs) return this
if(this instanceof SVG.Parent) return this.ungroup(parent, depth-1)
return this.toParent(parent)
})
this.node.firstChild || this.remove()
return this
},
flatten: function(parent, depth) {
return this.ungroup(parent, depth)
}
})
SVG.Container = SVG.invent({
// Initialize node
create: function(element) {
this.constructor.call(this, element)
}
// Inherit from
, inherit: SVG.Parent
})
SVG.ViewBox = SVG.invent({
create: function(source) {
var i, base = [0, 0, 0, 0]
var x, y, width, height, box, view, we, he
, wm = 1 // width multiplier
, hm = 1 // height multiplier
, reg = /[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?/gi
if(source instanceof SVG.Element){
we = source
he = source
view = (source.attr('viewBox') || '').match(reg)
box = source.bbox
// get dimensions of current node
width = new SVG.Number(source.width())
height = new SVG.Number(source.height())
// find nearest non-percentual dimensions
while (width.unit == '%') {
wm *= width.value
width = new SVG.Number(we instanceof SVG.Doc ? we.parent().offsetWidth : we.parent().width())
we = we.parent()
}
while (height.unit == '%') {
hm *= height.value
height = new SVG.Number(he instanceof SVG.Doc ? he.parent().offsetHeight : he.parent().height())
he = he.parent()
}
// ensure defaults
this.x = 0
this.y = 0
this.width = width * wm
this.height = height * hm
this.zoom = 1
if (view) {
// get width and height from viewbox
x = parseFloat(view[0])
y = parseFloat(view[1])
width = parseFloat(view[2])
height = parseFloat(view[3])
// calculate zoom accoring to viewbox
this.zoom = ((this.width / this.height) > (width / height)) ?
this.height / height :
this.width / width
// calculate real pixel dimensions on parent SVG.Doc element
this.x = x
this.y = y
this.width = width
this.height = height
}
}else{
// ensure source as object
source = typeof source === 'string' ?
source.match(reg).map(function(el){ return parseFloat(el) }) :
Array.isArray(source) ?
source :
typeof source == 'object' ?
[source.x, source.y, source.width, source.height] :
arguments.length == 4 ?
[].slice.call(arguments) :
base
this.x = source[0]
this.y = source[1]
this.width = source[2]
this.height = source[3]
}
}
, extend: {
toString: function() {
return this.x + ' ' + this.y + ' ' + this.width + ' ' + this.height
}
, morph: function(x, y, width, height){
this.destination = new SVG.ViewBox(x, y, width, height)
return this
}
, at: function(pos) {
if(!this.destination) return this
return new SVG.ViewBox([
this.x + (this.destination.x - this.x) * pos
, this.y + (this.destination.y - this.y) * pos
, this.width + (this.destination.width - this.width) * pos
, this.height + (this.destination.height - this.height) * pos
])
}
}
// Define parent
, parent: SVG.Container
// Add parent method
, construct: {
// get/set viewbox
viewbox: function(x, y, width, height) {
if (arguments.length == 0)
// act as a getter if there are no arguments
return new SVG.ViewBox(this)
// otherwise act as a setter
return this.attr('viewBox', new SVG.ViewBox(x, y, width, height))
}
}
})
// Add events to elements
;[ 'click'
, 'dblclick'
, 'mousedown'
, 'mouseup'
, 'mouseover'
, 'mouseout'
, 'mousemove'
// , 'mouseenter' -> not supported by IE
// , 'mouseleave' -> not supported by IE
, 'touchstart'
, 'touchmove'
, 'touchleave'
, 'touchend'
, 'touchcancel' ].forEach(function(event) {
// add event to SVG.Element
SVG.Element.prototype[event] = function(f) {
// bind event to element rather than element node
SVG.on(this.node, event, f)
return this
}
})
// Initialize listeners stack
SVG.listeners = []
SVG.handlerMap = []
SVG.listenerId = 0
// Add event binder in the SVG namespace
SVG.on = function(node, event, listener, binding, options) {
// create listener, get object-index
var l = listener.bind(binding || node.instance || node)
, index = (SVG.handlerMap.indexOf(node) + 1 || SVG.handlerMap.push(node)) - 1
, ev = event.split('.')[0]
, ns = event.split('.')[1] || '*'
// ensure valid object
SVG.listeners[index] = SVG.listeners[index] || {}
SVG.listeners[index][ev] = SVG.listeners[index][ev] || {}
SVG.listeners[index][ev][ns] = SVG.listeners[index][ev][ns] || {}
if(!listener._svgjsListenerId)
listener._svgjsListenerId = ++SVG.listenerId
// reference listener
SVG.listeners[index][ev][ns][listener._svgjsListenerId] = l
// add listener
node.addEventListener(ev, l, options || false)
}
// Add event unbinder in the SVG namespace
SVG.off = function(node, event, listener) {
var index = SVG.handlerMap.indexOf(node)
, ev = event && event.split('.')[0]
, ns = event && event.split('.')[1]
, namespace = ''
if(index == -1) return
if (listener) {
if(typeof listener == 'function') listener = listener._svgjsListenerId
if(!listener) return
// remove listener reference
if (SVG.listeners[index][ev] && SVG.listeners[index][ev][ns || '*']) {
// remove listener
node.removeEventListener(ev, SVG.listeners[index][ev][ns || '*'][listener], false)
delete SVG.listeners[index][ev][ns || '*'][listener]
}
} else if (ns && ev) {
// remove all listeners for a namespaced event
if (SVG.listeners[index][ev] && SVG.listeners[index][ev][ns]) {
for (listener in SVG.listeners[index][ev][ns])
SVG.off(node, [ev, ns].join('.'), listener)
delete SVG.listeners[index][ev][ns]
}
} else if (ns){
// remove all listeners for a specific namespace
for(event in SVG.listeners[index]){
for(namespace in SVG.listeners[index][event]){
if(ns === namespace){
SVG.off(node, [event, ns].join('.'))
}
}
}
} else if (ev) {
// remove all listeners for the event
if (SVG.listeners[index][ev]) {
for (namespace in SVG.listeners[index][ev])
SVG.off(node, [ev, namespace].join('.'))
delete SVG.listeners[index][ev]
}
} else {
// remove all listeners on a given node
for (event in SVG.listeners[index])
SVG.off(node, event)
delete SVG.listeners[index]
delete SVG.handlerMap[index]
}
}
//
SVG.extend(SVG.Element, {
// Bind given event to listener
on: function(event, listener, binding, options) {
SVG.on(this.node, event, listener, binding, options)
return this
}
// Unbind event from listener
, off: function(event, listener) {
SVG.off(this.node, event, listener)
return this
}
// Fire given event
, fire: function(event, data) {
// Dispatch event
if(event instanceof window.Event){
this.node.dispatchEvent(event)
}else{
this.node.dispatchEvent(event = new window.CustomEvent(event, {detail:data, cancelable: true}))
}
this._event = event
return this
}
, event: function() {
return this._event
}
})
SVG.Defs = SVG.invent({
// Initialize node
create: 'defs'
// Inherit from
, inherit: SVG.Container
})
SVG.G = SVG.invent({
// Initialize node
create: 'g'
// Inherit from
, inherit: SVG.Container
// Add class methods
, extend: {
// Move over x-axis
x: function(x) {
return x == null ? this.transform('x') : this.transform({ x: x - this.x() }, true)
}
// Move over y-axis
, y: function(y) {
return y == null ? this.transform('y') : this.transform({ y: y - this.y() }, true)
}
// Move by center over x-axis
, cx: function(x) {
return x == null ? this.gbox().cx : this.x(x - this.gbox().width / 2)
}
// Move by center over y-axis
, cy: function(y) {
return y == null ? this.gbox().cy : this.y(y - this.gbox().height / 2)
}
, gbox: function() {
var bbox = this.bbox()
, trans = this.transform()
bbox.x += trans.x
bbox.x2 += trans.x
bbox.cx += trans.x
bbox.y += trans.y
bbox.y2 += trans.y
bbox.cy += trans.y
return bbox
}
}
// Add parent method
, construct: {
// Create a group element
group: function() {
return this.put(new SVG.G)
}
}
})
// ### This module adds backward / forward functionality to elements.
//
SVG.extend(SVG.Element, {
// Get all siblings, including myself
siblings: function() {
return this.parent().children()
}
// Get the curent position siblings
, position: function() {
return this.parent().index(this)
}
// Get the next element (will return null if there is none)
, next: function() {
return this.siblings()[this.position() + 1]
}
// Get the next element (will return null if there is none)
, previous: function() {
return this.siblings()[this.position() - 1]
}
// Send given element one step forward
, forward: function() {
var i = this.position() + 1
, p = this.parent()
// move node one step forward
p.removeElement(this).add(this, i)
// make sure defs node is always at the top
if (p instanceof SVG.Doc)
p.node.appendChild(p.defs().node)
return this
}
// Send given element one step backward
, backward: function() {
var i = this.position()
if (i > 0)
this.parent().removeElement(this).add(this, i - 1)
return this
}
// Send given element all the way to the front
, front: function() {
var p = this.parent()
// Move node forward
p.node.appendChild(this.node)
// Make sure defs node is always at the top
if (p instanceof SVG.Doc)
p.node.appendChild(p.defs().node)
return this
}
// Send given element all the way to the back
, back: function() {
if (this.position() > 0)
this.parent().removeElement(this).add(this, 0)
return this
}
// Inserts a given element before the targeted element
, before: function(element) {
element.remove()
var i = this.position()
this.parent().add(element, i)
return this
}
// Insters a given element after the targeted element
, after: function(element) {
element.remove()
var i = this.position()
this.parent().add(element, i + 1)
return this
}
})
SVG.Mask = SVG.invent({
// Initialize node
create: function() {
this.constructor.call(this, SVG.create('mask'))
// keep references to masked elements
this.targets = []
}
// Inherit from
, inherit: SVG.Container
// Add class methods
, extend: {
// Unmask all masked elements and remove itself
remove: function() {
// unmask all targets
for (var i = this.targets.length - 1; i >= 0; i--)
if (this.targets[i])
this.targets[i].unmask()
this.targets = []
// remove mask from parent
this.parent().removeElement(this)
return this
}
}
// Add parent method
, construct: {
// Create masking element
mask: function() {
return this.defs().put(new SVG.Mask)
}
}
})
SVG.extend(SVG.Element, {
// Distribute mask to svg element
maskWith: function(element) {
// use given mask or create a new one
this.masker = element instanceof SVG.Mask ? element : this.parent().mask().add(element)
// store reverence on self in mask
this.masker.targets.push(this)
// apply mask
return this.attr('mask', 'url("#' + this.masker.attr('id') + '")')
}
// Unmask element
, unmask: function() {
delete this.masker
return this.attr('mask', null)
}
})
SVG.ClipPath = SVG.invent({
// Initialize node
create: function() {
this.constructor.call(this, SVG.create('clipPath'))
// keep references to clipped elements
this.targets = []
}
// Inherit from
, inherit: SVG.Container
// Add class methods
, extend: {
// Unclip all clipped elements and remove itself
remove: function() {
// unclip all targets
for (var i = this.targets.length - 1; i >= 0; i--)
if (this.targets[i])
this.targets[i].unclip()
this.targets = []
// remove clipPath from parent
this.parent().removeElement(this)
return this
}
}
// Add parent method
, construct: {
// Create clipping element
clip: function() {
return this.defs().put(new SVG.ClipPath)
}
}
})
//
SVG.extend(SVG.Element, {
// Distribute clipPath to svg element
clipWith: function(element) {
// use given clip or create a new one
this.clipper = element instanceof SVG.ClipPath ? element : this.parent().clip().add(element)
// store reverence on self in mask
this.clipper.targets.push(this)
// apply mask
return this.attr('clip-path', 'url("#' + this.clipper.attr('id') + '")')
}
// Unclip element
, unclip: function() {
delete this.clipper
return this.attr('clip-path', null)
}
})
SVG.Gradient = SVG.invent({
// Initialize node
create: function(type) {
this.constructor.call(this, SVG.create(type + 'Gradient'))
// store type
this.type = type
}
// Inherit from
, inherit: SVG.Container
// Add class methods
, extend: {
// Add a color stop
at: function(offset, color, opacity) {
return this.put(new SVG.Stop).update(offset, color, opacity)
}
// Update gradient
, update: function(block) {
// remove all stops
this.clear()
// invoke passed block
if (typeof block == 'function')
block.call(this, this)
return this
}
// Return the fill id
, fill: function() {
return 'url(#' + this.id() + ')'
}
// Alias string convertion to fill
, toString: function() {
return this.fill()
}
// custom attr to handle transform
, attr: function(a, b, c) {
if(a == 'transform') a = 'gradientTransform'
return SVG.Container.prototype.attr.call(this, a, b, c)
}
}
// Add parent method
, construct: {
// Create gradient element in defs
gradient: function(type, block) {
return this.defs().gradient(type, block)
}
}
})
// Add animatable methods to both gradient and fx module
SVG.extend(SVG.Gradient, SVG.FX, {
// From position
from: function(x, y) {
return (this._target || this).type == 'radial' ?
this.attr({ fx: new SVG.Number(x), fy: new SVG.Number(y) }) :
this.attr({ x1: new SVG.Number(x), y1: new SVG.Number(y) })
}
// To position
, to: function(x, y) {
return (this._target || this).type == 'radial' ?
this.attr({ cx: new SVG.Number(x), cy: new SVG.Number(y) }) :
this.attr({ x2: new SVG.Number(x), y2: new SVG.Number(y) })
}
})
// Base gradient generation
SVG.extend(SVG.Defs, {
// define gradient
gradient: function(type, block) {
return this.put(new SVG.Gradient(type)).update(block)
}
})
SVG.Stop = SVG.invent({
// Initialize node
create: 'stop'
// Inherit from
, inherit: SVG.Element
// Add class methods
, extend: {
// add color stops
update: function(o) {
if (typeof o == 'number' || o instanceof SVG.Number) {
o = {
offset: arguments[0]
, color: arguments[1]
, opacity: arguments[2]
}
}
// set attributes
if (o.opacity != null) this.attr('stop-opacity', o.opacity)
if (o.color != null) this.attr('stop-color', o.color)
if (o.offset != null) this.attr('offset', new SVG.Number(o.offset))
return this
}
}
})
SVG.Pattern = SVG.invent({
// Initialize node
create: 'pattern'
// Inherit from
, inherit: SVG.Container
// Add class methods
, extend: {
// Return the fill id
fill: function() {
return 'url(#' + this.id() + ')'
}
// Update pattern by rebuilding
, update: function(block) {
// remove content
this.clear()
// invoke passed block
if (typeof block == 'function')
block.call(this, this)
return this
}
// Alias string convertion to fill
, toString: function() {
return this.fill()
}
// custom attr to handle transform
, attr: function(a, b, c) {
if(a == 'transform') a = 'patternTransform'
return SVG.Container.prototype.attr.call(this, a, b, c)
}
}
// Add parent method
, construct: {
// Create pattern element in defs
pattern: function(width, height, block) {
return this.defs().pattern(width, height, block)
}
}
})
SVG.extend(SVG.Defs, {
// Define gradient
pattern: function(width, height, block) {
return this.put(new SVG.Pattern).update(block).attr({
x: 0
, y: 0
, width: width
, height: height
, patternUnits: 'userSpaceOnUse'
})
}
})
SVG.Doc = SVG.invent({
// Initialize node
create: function(element) {
if (element) {
// ensure the presence of a dom element
element = typeof element == 'string' ?
document.getElementById(element) :
element
// If the target is an svg element, use that element as the main wrapper.
// This allows svg.js to work with svg documents as well.
if (element.nodeName == 'svg') {
this.constructor.call(this, element)
} else {
this.constructor.call(this, SVG.create('svg'))
element.appendChild(this.node)
this.size('100%', '100%')
}
// set svg element attributes and ensure defs node
this.namespace().defs()
}
}
// Inherit from
, inherit: SVG.Container
// Add class methods
, extend: {
// Add namespaces
namespace: function() {
return this
.attr({ xmlns: SVG.ns, version: '1.1' })
.attr('xmlns:xlink', SVG.xlink, SVG.xmlns)
.attr('xmlns:svgjs', SVG.svgjs, SVG.xmlns)
}
// Creates and returns defs element
, defs: function() {
if (!this._defs) {
var defs
// Find or create a defs element in this instance
if (defs = this.node.getElementsByTagName('defs')[0])
this._defs = SVG.adopt(defs)
else
this._defs = new SVG.Defs
// Make sure the defs node is at the end of the stack
this.node.appendChild(this._defs.node)
}
return this._defs
}
// custom parent method
, parent: function() {
return this.node.parentNode.nodeName == '#document' ? null : this.node.parentNode
}
// Fix for possible sub-pixel offset. See:
// https://bugzilla.mozilla.org/show_bug.cgi?id=608812
, spof: function(spof) {
var pos = this.node.getScreenCTM()
if (pos)
this
.style('left', (-pos.e % 1) + 'px')
.style('top', (-pos.f % 1) + 'px')
return this
}
// Removes the doc from the DOM
, remove: function() {
if(this.parent()) {
this.parent().removeChild(this.node)
}
return this
}
, clear: function() {
// remove children
while(this.node.hasChildNodes())
this.node.removeChild(this.node.lastChild)
// remove defs reference
delete this._defs
// add back parser
if(!SVG.parser.draw.parentNode)
this.node.appendChild(SVG.parser.draw)
return this
}
}
})
SVG.Shape = SVG.invent({
// Initialize node
create: function(element) {
this.constructor.call(this, element)
}
// Inherit from
, inherit: SVG.Element
})
SVG.Bare = SVG.invent({
// Initialize
create: function(element, inherit) {
// construct element
this.constructor.call(this, SVG.create(element))
// inherit custom methods
if (inherit)
for (var method in inherit.prototype)
if (typeof inherit.prototype[method] === 'function')
this[method] = inherit.prototype[method]
}
// Inherit from
, inherit: SVG.Element
// Add methods
, extend: {
// Insert some plain text
words: function(text) {
// remove contents
while (this.node.hasChildNodes())
this.node.removeChild(this.node.lastChild)
// create text node
this.node.appendChild(document.createTextNode(text))
return this
}
}
})
SVG.extend(SVG.Parent, {
// Create an element that is not described by SVG.js
element: function(element, inherit) {
return this.put(new SVG.Bare(element, inherit))
}
})
SVG.Symbol = SVG.invent({
// Initialize node
create: 'symbol'
// Inherit from
, inherit: SVG.Container
, construct: {
// create symbol
symbol: function() {
return this.put(new SVG.Symbol)
}
}
})
SVG.Use = SVG.invent({
// Initialize node
create: 'use'
// Inherit from
, inherit: SVG.Shape
// Add class methods
, extend: {
// Use element as a reference
element: function(element, file) {
// Set lined element
return this.attr('href', (file || '') + '#' + element, SVG.xlink)
}
}
// Add parent method
, construct: {
// Create a use element
use: function(element, file) {
return this.put(new SVG.Use).element(element, file)
}
}
})
SVG.Rect = SVG.invent({
// Initialize node
create: 'rect'
// Inherit from
, inherit: SVG.Shape
// Add parent method
, construct: {
// Create a rect element
rect: function(width, height) {
return this.put(new SVG.Rect()).size(width, height)
}
}
})
SVG.Circle = SVG.invent({
// Initialize node
create: 'circle'
// Inherit from
, inherit: SVG.Shape
// Add parent method
, construct: {
// Create circle element, based on ellipse
circle: function(size) {
return this.put(new SVG.Circle).rx(new SVG.Number(size).divide(2)).move(0, 0)
}
}
})
SVG.extend(SVG.Circle, SVG.FX, {
// Radius x value
rx: function(rx) {
return this.attr('r', rx)
}
// Alias radius x value
, ry: function(ry) {
return this.rx(ry)
}
})
SVG.Ellipse = SVG.invent({
// Initialize node
create: 'ellipse'
// Inherit from
, inherit: SVG.Shape
// Add parent method
, construct: {
// Create an ellipse
ellipse: function(width, height) {
return this.put(new SVG.Ellipse).size(width, height).move(0, 0)
}
}
})
SVG.extend(SVG.Ellipse, SVG.Rect, SVG.FX, {
// Radius x value
rx: function(rx) {
return this.attr('rx', rx)
}
// Radius y value
, ry: function(ry) {
return this.attr('ry', ry)
}
})
// Add common method
SVG.extend(SVG.Circle, SVG.Ellipse, {
// Move over x-axis
x: function(x) {
return x == null ? this.cx() - this.rx() : this.cx(x + this.rx())
}
// Move over y-axis
, y: function(y) {
return y == null ? this.cy() - this.ry() : this.cy(y + this.ry())
}
// Move by center over x-axis
, cx: function(x) {
return x == null ? this.attr('cx') : this.attr('cx', x)
}
// Move by center over y-axis
, cy: function(y) {
return y == null ? this.attr('cy') : this.attr('cy', y)
}
// Set width of element
, width: function(width) {
return width == null ? this.rx() * 2 : this.rx(new SVG.Number(width).divide(2))
}
// Set height of element
, height: function(height) {
return height == null ? this.ry() * 2 : this.ry(new SVG.Number(height).divide(2))
}
// Custom size function
, size: function(width, height) {
var p = proportionalSize(this, width, height)
return this
.rx(new SVG.Number(p.width).divide(2))
.ry(new SVG.Number(p.height).divide(2))
}
})
SVG.Line = SVG.invent({
// Initialize node
create: 'line'
// Inherit from
, inherit: SVG.Shape
// Add class methods
, extend: {
// Get array
array: function() {
return new SVG.PointArray([
[ this.attr('x1'), this.attr('y1') ]
, [ this.attr('x2'), this.attr('y2') ]
])
}
// Overwrite native plot() method
, plot: function(x1, y1, x2, y2) {
if (x1 == null)
return this.array()
else if (typeof y1 !== 'undefined')
x1 = { x1: x1, y1: y1, x2: x2, y2: y2 }
else
x1 = new SVG.PointArray(x1).toLine()
return this.attr(x1)
}
// Move by left top corner
, move: function(x, y) {
return this.attr(this.array().move(x, y).toLine())
}
// Set element size to given width and height
, size: function(width, height) {
var p = proportionalSize(this, width, height)
return this.attr(this.array().size(p.width, p.height).toLine())
}
}
// Add parent method
, construct: {
// Create a line element
line: function(x1, y1, x2, y2) {
// make sure plot is called as a setter
// x1 is not necessarily a number, it can also be an array, a string and a SVG.PointArray
return SVG.Line.prototype.plot.apply(
this.put(new SVG.Line)
, x1 != null ? [x1, y1, x2, y2] : [0, 0, 0, 0]
)
}
}
})
SVG.Polyline = SVG.invent({
// Initialize node
create: 'polyline'
// Inherit from
, inherit: SVG.Shape
// Add parent method
, construct: {
// Create a wrapped polyline element
polyline: function(p) {
// make sure plot is called as a setter
return this.put(new SVG.Polyline).plot(p || new SVG.PointArray)
}
}
})
SVG.Polygon = SVG.invent({
// Initialize node
create: 'polygon'
// Inherit from
, inherit: SVG.Shape
// Add parent method
, construct: {
// Create a wrapped polygon element
polygon: function(p) {
// make sure plot is called as a setter
return this.put(new SVG.Polygon).plot(p || new SVG.PointArray)
}
}
})
// Add polygon-specific functions
SVG.extend(SVG.Polyline, SVG.Polygon, {
// Get array
array: function() {
return this._array || (this._array = new SVG.PointArray(this.attr('points')))
}
// Plot new path
, plot: function(p) {
return (p == null) ?
this.array() :
this.clear().attr('points', typeof p == 'string' ? p : (this._array = new SVG.PointArray(p)))
}
// Clear array cache
, clear: function() {
delete this._array
return this
}
// Move by left top corner
, move: function(x, y) {
return this.attr('points', this.array().move(x, y))
}
// Set element size to given width and height
, size: function(width, height) {
var p = proportionalSize(this, width, height)
return this.attr('points', this.array().size(p.width, p.height))
}
})
// unify all point to point elements
SVG.extend(SVG.Line, SVG.Polyline, SVG.Polygon, {
// Define morphable array
morphArray: SVG.PointArray
// Move by left top corner over x-axis
, x: function(x) {
return x == null ? this.bbox().x : this.move(x, this.bbox().y)
}
// Move by left top corner over y-axis
, y: function(y) {
return y == null ? this.bbox().y : this.move(this.bbox().x, y)
}
// Set width of element
, width: function(width) {
var b = this.bbox()
return width == null ? b.width : this.size(width, b.height)
}
// Set height of element
, height: function(height) {
var b = this.bbox()
return height == null ? b.height : this.size(b.width, height)
}
})
SVG.Path = SVG.invent({
// Initialize node
create: 'path'
// Inherit from
, inherit: SVG.Shape
// Add class methods
, extend: {
// Define morphable array
morphArray: SVG.PathArray
// Get array
, array: function() {
return this._array || (this._array = new SVG.PathArray(this.attr('d')))
}
// Plot new path
, plot: function(d) {
return (d == null) ?
this.array() :
this.clear().attr('d', typeof d == 'string' ? d : (this._array = new SVG.PathArray(d)))
}
// Clear array cache
, clear: function() {
delete this._array
return this
}
// Move by left top corner
, move: function(x, y) {
return this.attr('d', this.array().move(x, y))
}
// Move by left top corner over x-axis
, x: function(x) {
return x == null ? this.bbox().x : this.move(x, this.bbox().y)
}
// Move by left top corner over y-axis
, y: function(y) {
return y == null ? this.bbox().y : this.move(this.bbox().x, y)
}
// Set element size to given width and height
, size: function(width, height) {
var p = proportionalSize(this, width, height)
return this.attr('d', this.array().size(p.width, p.height))
}
// Set width of element
, width: function(width) {
return width == null ? this.bbox().width : this.size(width, this.bbox().height)
}
// Set height of element
, height: function(height) {
return height == null ? this.bbox().height : this.size(this.bbox().width, height)
}
}
// Add parent method
, construct: {
// Create a wrapped path element
path: function(d) {
// make sure plot is called as a setter
return this.put(new SVG.Path).plot(d || new SVG.PathArray)
}
}
})
SVG.Image = SVG.invent({
// Initialize node
create: 'image'
// Inherit from
, inherit: SVG.Shape
// Add class methods
, extend: {
// (re)load image
load: function(url) {
if (!url) return this
var self = this
, img = new window.Image()
// preload image
SVG.on(img, 'load', function() {
var p = self.parent(SVG.Pattern)
if(p === null) return
// ensure image size
if (self.width() == 0 && self.height() == 0)
self.size(img.width, img.height)
// ensure pattern size if not set
if (p && p.width() == 0 && p.height() == 0)
p.size(self.width(), self.height())
// callback
if (typeof self._loaded === 'function')
self._loaded.call(self, {
width: img.width
, height: img.height
, ratio: img.width / img.height
, url: url
})
})
SVG.on(img, 'error', function(e){
if (typeof self._error === 'function'){
self._error.call(self, e)
}
})
return this.attr('href', (img.src = this.src = url), SVG.xlink)
}
// Add loaded callback
, loaded: function(loaded) {
this._loaded = loaded
return this
}
, error: function(error) {
this._error = error
return this
}
}
// Add parent method
, construct: {
// create image element, load image and set its size
image: function(source, width, height) {
return this.put(new SVG.Image).load(source).size(width || 0, height || width || 0)
}
}
})
SVG.Text = SVG.invent({
// Initialize node
create: function() {
this.constructor.call(this, SVG.create('text'))
this.dom.leading = new SVG.Number(1.3) // store leading value for rebuilding
this._rebuild = true // enable automatic updating of dy values
this._build = false // disable build mode for adding multiple lines
// set default font
this.attr('font-family', SVG.defaults.attrs['font-family'])
}
// Inherit from
, inherit: SVG.Shape
// Add class methods
, extend: {
// Move over x-axis
x: function(x) {
// act as getter
if (x == null)
return this.attr('x')
return this.attr('x', x)
}
// Move over y-axis
, y: function(y) {
var oy = this.attr('y')
, o = typeof oy === 'number' ? oy - this.bbox().y : 0
// act as getter
if (y == null)
return typeof oy === 'number' ? oy - o : oy
return this.attr('y', typeof y === 'number' ? y + o : y)
}
// Move center over x-axis
, cx: function(x) {
return x == null ? this.bbox().cx : this.x(x - this.bbox().width / 2)
}
// Move center over y-axis
, cy: function(y) {
return y == null ? this.bbox().cy : this.y(y - this.bbox().height / 2)
}
// Set the text content
, text: function(text) {
// act as getter
if (typeof text === 'undefined'){
var text = ''
var children = this.node.childNodes
for(var i = 0, len = children.length; i < len; ++i){
// add newline if its not the first child and newLined is set to true
if(i != 0 && children[i].nodeType != 3 && SVG.adopt(children[i]).dom.newLined == true){
text += '\n'
}
// add content of this node
text += children[i].textContent
}
return text
}
// remove existing content
this.clear().build(true)
if (typeof text === 'function') {
// call block
text.call(this, this)
} else {
// store text and make sure text is not blank
text = text.split('\n')
// build new lines
for (var i = 0, il = text.length; i < il; i++)
this.tspan(text[i]).newLine()
}
// disable build mode and rebuild lines
return this.build(false).rebuild()
}
// Set font size
, size: function(size) {
return this.attr('font-size', size).rebuild()
}
// Set / get leading
, leading: function(value) {
// act as getter
if (value == null)
return this.dom.leading
// act as setter
this.dom.leading = new SVG.Number(value)
return this.rebuild()
}
// Get all the first level lines
, lines: function() {
var node = (this.textPath && this.textPath() || this).node
// filter tspans and map them to SVG.js instances
var lines = SVG.utils.map(SVG.utils.filterSVGElements(node.childNodes), function(el){
return SVG.adopt(el)
})
// return an instance of SVG.set
return new SVG.Set(lines)
}
// Rebuild appearance type
, rebuild: function(rebuild) {
// store new rebuild flag if given
if (typeof rebuild == 'boolean')
this._rebuild = rebuild
// define position of all lines
if (this._rebuild) {
var self = this
, blankLineOffset = 0
, dy = this.dom.leading * new SVG.Number(this.attr('font-size'))
this.lines().each(function() {
if (this.dom.newLined) {
if (!self.textPath())
this.attr('x', self.attr('x'))
if(this.text() == '\n') {
blankLineOffset += dy
}else{
this.attr('dy', dy + blankLineOffset)
blankLineOffset = 0
}
}
})
this.fire('rebuild')
}
return this
}
// Enable / disable build mode
, build: function(build) {
this._build = !!build
return this
}
// overwrite method from parent to set data properly
, setData: function(o){
this.dom = o
this.dom.leading = new SVG.Number(o.leading || 1.3)
return this
}
}
// Add parent method
, construct: {
// Create text element
text: function(text) {
return this.put(new SVG.Text).text(text)
}
// Create plain text element
, plain: function(text) {
return this.put(new SVG.Text).plain(text)
}
}
})
SVG.Tspan = SVG.invent({
// Initialize node
create: 'tspan'
// Inherit from
, inherit: SVG.Shape
// Add class methods
, extend: {
// Set text content
text: function(text) {
if(text == null) return this.node.textContent + (this.dom.newLined ? '\n' : '')
typeof text === 'function' ? text.call(this, this) : this.plain(text)
return this
}
// Shortcut dx
, dx: function(dx) {
return this.attr('dx', dx)
}
// Shortcut dy
, dy: function(dy) {
return this.attr('dy', dy)
}
// Create new line
, newLine: function() {
// fetch text parent
var t = this.parent(SVG.Text)
// mark new line
this.dom.newLined = true
// apply new hy¡n
return this.dy(t.dom.leading * t.attr('font-size')).attr('x', t.x())
}
}
})
SVG.extend(SVG.Text, SVG.Tspan, {
// Create plain text node
plain: function(text) {
// clear if build mode is disabled
if (this._build === false)
this.clear()
// create text node
this.node.appendChild(document.createTextNode(text))
return this
}
// Create a tspan
, tspan: function(text) {
var node = (this.textPath && this.textPath() || this).node
, tspan = new SVG.Tspan
// clear if build mode is disabled
if (this._build === false)
this.clear()
// add new tspan
node.appendChild(tspan.node)
return tspan.text(text)
}
// Clear all lines
, clear: function() {
var node = (this.textPath && this.textPath() || this).node
// remove existing child nodes
while (node.hasChildNodes())
node.removeChild(node.lastChild)
return this
}
// Get length of text element
, length: function() {
return this.node.getComputedTextLength()
}
})
SVG.TextPath = SVG.invent({
// Initialize node
create: 'textPath'
// Inherit from
, inherit: SVG.Parent
// Define parent class
, parent: SVG.Text
// Add parent method
, construct: {
// Create path for text to run on
path: function(d) {
// create textPath element
var path = new SVG.TextPath
, track = this.doc().defs().path(d)
// move lines to textpath
while (this.node.hasChildNodes())
path.node.appendChild(this.node.firstChild)
// add textPath element as child node
this.node.appendChild(path.node)
// link textPath to path and add content
path.attr('href', '#' + track, SVG.xlink)
return this
}
// return the array of the path track element
, array: function() {
var track = this.track()
return track ? track.array() : null
}
// Plot path if any
, plot: function(d) {
var track = this.track()
, pathArray = null
if (track) {
pathArray = track.plot(d)
}
return (d == null) ? pathArray : this
}
// Get the path track element
, track: function() {
var path = this.textPath()
if (path)
return path.reference('href')
}
// Get the textPath child
, textPath: function() {
if (this.node.firstChild && this.node.firstChild.nodeName == 'textPath')
return SVG.adopt(this.node.firstChild)
}
}
})
SVG.Nested = SVG.invent({
// Initialize node
create: function() {
this.constructor.call(this, SVG.create('svg'))
this.style('overflow', 'visible')
}
// Inherit from
, inherit: SVG.Container
// Add parent method
, construct: {
// Create nested svg document
nested: function() {
return this.put(new SVG.Nested)
}
}
})
SVG.A = SVG.invent({
// Initialize node
create: 'a'
// Inherit from
, inherit: SVG.Container
// Add class methods
, extend: {
// Link url
to: function(url) {
return this.attr('href', url, SVG.xlink)
}
// Link show attribute
, show: function(target) {
return this.attr('show', target, SVG.xlink)
}
// Link target attribute
, target: function(target) {
return this.attr('target', target)
}
}
// Add parent method
, construct: {
// Create a hyperlink element
link: function(url) {
return this.put(new SVG.A).to(url)
}
}
})
SVG.extend(SVG.Element, {
// Create a hyperlink element
linkTo: function(url) {
var link = new SVG.A
if (typeof url == 'function')
url.call(link, link)
else
link.to(url)
return this.parent().put(link).put(this)
}
})
SVG.Marker = SVG.invent({
// Initialize node
create: 'marker'
// Inherit from
, inherit: SVG.Container
// Add class methods
, extend: {
// Set width of element
width: function(width) {
return this.attr('markerWidth', width)
}
// Set height of element
, height: function(height) {
return this.attr('markerHeight', height)
}
// Set marker refX and refY
, ref: function(x, y) {
return this.attr('refX', x).attr('refY', y)
}
// Update marker
, update: function(block) {
// remove all content
this.clear()
// invoke passed block
if (typeof block == 'function')
block.call(this, this)
return this
}
// Return the fill id
, toString: function() {
return 'url(#' + this.id() + ')'
}
}
// Add parent method
, construct: {
marker: function(width, height, block) {
// Create marker element in defs
return this.defs().marker(width, height, block)
}
}
})
SVG.extend(SVG.Defs, {
// Create marker
marker: function(width, height, block) {
// Set default viewbox to match the width and height, set ref to cx and cy and set orient to auto
return this.put(new SVG.Marker)
.size(width, height)
.ref(width / 2, height / 2)
.viewbox(0, 0, width, height)
.attr('orient', 'auto')
.update(block)
}
})
SVG.extend(SVG.Line, SVG.Polyline, SVG.Polygon, SVG.Path, {
// Create and attach markers
marker: function(marker, width, height, block) {
var attr = ['marker']
// Build attribute name
if (marker != 'all') attr.push(marker)
attr = attr.join('-')
// Set marker attribute
marker = arguments[1] instanceof SVG.Marker ?
arguments[1] :
this.doc().marker(width, height, block)
return this.attr(attr, marker)
}
})
// Define list of available attributes for stroke and fill
var sugar = {
stroke: ['color', 'width', 'opacity', 'linecap', 'linejoin', 'miterlimit', 'dasharray', 'dashoffset']
, fill: ['color', 'opacity', 'rule']
, prefix: function(t, a) {
return a == 'color' ? t : t + '-' + a
}
}
// Add sugar for fill and stroke
;['fill', 'stroke'].forEach(function(m) {
var i, extension = {}
extension[m] = function(o) {
if (typeof o == 'undefined')
return this
if (typeof o == 'string' || SVG.Color.isRgb(o) || (o && typeof o.fill === 'function'))
this.attr(m, o)
else
// set all attributes from sugar.fill and sugar.stroke list
for (i = sugar[m].length - 1; i >= 0; i--)
if (o[sugar[m][i]] != null)
this.attr(sugar.prefix(m, sugar[m][i]), o[sugar[m][i]])
return this
}
SVG.extend(SVG.Element, SVG.FX, extension)
})
SVG.extend(SVG.Element, SVG.FX, {
// Map rotation to transform
rotate: function(d, cx, cy) {
return this.transform({ rotation: d, cx: cx, cy: cy })
}
// Map skew to transform
, skew: function(x, y, cx, cy) {
return arguments.length == 1 || arguments.length == 3 ?
this.transform({ skew: x, cx: y, cy: cx }) :
this.transform({ skewX: x, skewY: y, cx: cx, cy: cy })
}
// Map scale to transform
, scale: function(x, y, cx, cy) {
return arguments.length == 1 || arguments.length == 3 ?
this.transform({ scale: x, cx: y, cy: cx }) :
this.transform({ scaleX: x, scaleY: y, cx: cx, cy: cy })
}
// Map translate to transform
, translate: function(x, y) {
return this.transform({ x: x, y: y })
}
// Map flip to transform
, flip: function(a, o) {
o = typeof a == 'number' ? a : o
return this.transform({ flip: a || 'both', offset: o })
}
// Map matrix to transform
, matrix: function(m) {
return this.attr('transform', new SVG.Matrix(arguments.length == 6 ? [].slice.call(arguments) : m))
}
// Opacity
, opacity: function(value) {
return this.attr('opacity', value)
}
// Relative move over x axis
, dx: function(x) {
return this.x(new SVG.Number(x).plus(this instanceof SVG.FX ? 0 : this.x()), true)
}
// Relative move over y axis
, dy: function(y) {
return this.y(new SVG.Number(y).plus(this instanceof SVG.FX ? 0 : this.y()), true)
}
// Relative move over x and y axes
, dmove: function(x, y) {
return this.dx(x).dy(y)
}
})
SVG.extend(SVG.Rect, SVG.Ellipse, SVG.Circle, SVG.Gradient, SVG.FX, {
// Add x and y radius
radius: function(x, y) {
var type = (this._target || this).type;
return type == 'radial' || type == 'circle' ?
this.attr('r', new SVG.Number(x)) :
this.rx(x).ry(y == null ? x : y)
}
})
SVG.extend(SVG.Path, {
// Get path length
length: function() {
return this.node.getTotalLength()
}
// Get point at length
, pointAt: function(length) {
return this.node.getPointAtLength(length)
}
})
SVG.extend(SVG.Parent, SVG.Text, SVG.Tspan, SVG.FX, {
// Set font
font: function(a, v) {
if (typeof a == 'object') {
for (v in a) this.font(v, a[v])
}
return a == 'leading' ?
this.leading(v) :
a == 'anchor' ?
this.attr('text-anchor', v) :
a == 'size' || a == 'family' || a == 'weight' || a == 'stretch' || a == 'variant' || a == 'style' ?
this.attr('font-'+ a, v) :
this.attr(a, v)
}
})
SVG.Set = SVG.invent({
// Initialize
create: function(members) {
// Set initial state
Array.isArray(members) ? this.members = members : this.clear()
}
// Add class methods
, extend: {
// Add element to set
add: function() {
var i, il, elements = [].slice.call(arguments)
for (i = 0, il = elements.length; i < il; i++)
this.members.push(elements[i])
return this
}
// Remove element from set
, remove: function(element) {
var i = this.index(element)
// remove given child
if (i > -1)
this.members.splice(i, 1)
return this
}
// Iterate over all members
, each: function(block) {
for (var i = 0, il = this.members.length; i < il; i++)
block.apply(this.members[i], [i, this.members])
return this
}
// Restore to defaults
, clear: function() {
// initialize store
this.members = []
return this
}
// Get the length of a set
, length: function() {
return this.members.length
}
// Checks if a given element is present in set
, has: function(element) {
return this.index(element) >= 0
}
// retuns index of given element in set
, index: function(element) {
return this.members.indexOf(element)
}
// Get member at given index
, get: function(i) {
return this.members[i]
}
// Get first member
, first: function() {
return this.get(0)
}
// Get last member
, last: function() {
return this.get(this.members.length - 1)
}
// Default value
, valueOf: function() {
return this.members
}
// Get the bounding box of all members included or empty box if set has no items
, bbox: function(){
// return an empty box of there are no members
if (this.members.length == 0)
return new SVG.RBox()
// get the first rbox and update the target bbox
var rbox = this.members[0].rbox(this.members[0].doc())
this.each(function() {
// user rbox for correct position and visual representation
rbox = rbox.merge(this.rbox(this.doc()))
})
return rbox
}
}
// Add parent method
, construct: {
// Create a new set
set: function(members) {
return new SVG.Set(members)
}
}
})
SVG.FX.Set = SVG.invent({
// Initialize node
create: function(set) {
// store reference to set
this.set = set
}
})
// Alias methods
SVG.Set.inherit = function() {
var m
, methods = []
// gather shape methods
for(var m in SVG.Shape.prototype)
if (typeof SVG.Shape.prototype[m] == 'function' && typeof SVG.Set.prototype[m] != 'function')
methods.push(m)
// apply shape aliasses
methods.forEach(function(method) {
SVG.Set.prototype[method] = function() {
for (var i = 0, il = this.members.length; i < il; i++)
if (this.members[i] && typeof this.members[i][method] == 'function')
this.members[i][method].apply(this.members[i], arguments)
return method == 'animate' ? (this.fx || (this.fx = new SVG.FX.Set(this))) : this
}
})
// clear methods for the next round
methods = []
// gather fx methods
for(var m in SVG.FX.prototype)
if (typeof SVG.FX.prototype[m] == 'function' && typeof SVG.FX.Set.prototype[m] != 'function')
methods.push(m)
// apply fx aliasses
methods.forEach(function(method) {
SVG.FX.Set.prototype[method] = function() {
for (var i = 0, il = this.set.members.length; i < il; i++)
this.set.members[i].fx[method].apply(this.set.members[i].fx, arguments)
return this
}
})
}
SVG.extend(SVG.Element, {
// Store data values on svg nodes
data: function(a, v, r) {
if (typeof a == 'object') {
for (v in a)
this.data(v, a[v])
} else if (arguments.length < 2) {
try {
return JSON.parse(this.attr('data-' + a))
} catch(e) {
return this.attr('data-' + a)
}
} else {
this.attr(
'data-' + a
, v === null ?
null :
r === true || typeof v === 'string' || typeof v === 'number' ?
v :
JSON.stringify(v)
)
}
return this
}
})
SVG.extend(SVG.Element, {
// Remember arbitrary data
remember: function(k, v) {
// remember every item in an object individually
if (typeof arguments[0] == 'object')
for (var v in k)
this.remember(v, k[v])
// retrieve memory
else if (arguments.length == 1)
return this.memory()[k]
// store memory
else
this.memory()[k] = v
return this
}
// Erase a given memory
, forget: function() {
if (arguments.length == 0)
this._memory = {}
else
for (var i = arguments.length - 1; i >= 0; i--)
delete this.memory()[arguments[i]]
return this
}
// Initialize or return local memory object
, memory: function() {
return this._memory || (this._memory = {})
}
})
// Method for getting an element by id
SVG.get = function(id) {
var node = document.getElementById(idFromReference(id) || id)
return SVG.adopt(node)
}
// Select elements by query string
SVG.select = function(query, parent) {
return new SVG.Set(
SVG.utils.map((parent || document).querySelectorAll(query), function(node) {
return SVG.adopt(node)
})
)
}
SVG.extend(SVG.Parent, {
// Scoped select method
select: function(query) {
return SVG.select(query, this.node)
}
})
function pathRegReplace(a, b, c, d) {
return c + d.replace(SVG.regex.dots, ' .')
}
// creates deep clone of array
function array_clone(arr){
var clone = arr.slice(0)
for(var i = clone.length; i--;){
if(Array.isArray(clone[i])){
clone[i] = array_clone(clone[i])
}
}
return clone
}
// tests if a given element is instance of an object
function is(el, obj){
return el instanceof obj
}
// tests if a given selector matches an element
function matches(el, selector) {
return (el.matches || el.matchesSelector || el.msMatchesSelector || el.mozMatchesSelector || el.webkitMatchesSelector || el.oMatchesSelector).call(el, selector);
}
// Convert dash-separated-string to camelCase
function camelCase(s) {
return s.toLowerCase().replace(/-(.)/g, function(m, g) {
return g.toUpperCase()
})
}
// Capitalize first letter of a string
function capitalize(s) {
return s.charAt(0).toUpperCase() + s.slice(1)
}
// Ensure to six-based hex
function fullHex(hex) {
return hex.length == 4 ?
[ '#',
hex.substring(1, 2), hex.substring(1, 2)
, hex.substring(2, 3), hex.substring(2, 3)
, hex.substring(3, 4), hex.substring(3, 4)
].join('') : hex
}
// Component to hex value
function compToHex(comp) {
var hex = comp.toString(16)
return hex.length == 1 ? '0' + hex : hex
}
// Calculate proportional width and height values when necessary
function proportionalSize(element, width, height) {
if (width == null || height == null) {
var box = element.bbox()
if (width == null)
width = box.width / box.height * height
else if (height == null)
height = box.height / box.width * width
}
return {
width: width
, height: height
}
}
// Delta transform point
function deltaTransformPoint(matrix, x, y) {
return {
x: x * matrix.a + y * matrix.c + 0
, y: x * matrix.b + y * matrix.d + 0
}
}
// Map matrix array to object
function arrayToMatrix(a) {
return { a: a[0], b: a[1], c: a[2], d: a[3], e: a[4], f: a[5] }
}
// Parse matrix if required
function parseMatrix(matrix) {
if (!(matrix instanceof SVG.Matrix))
matrix = new SVG.Matrix(matrix)
return matrix
}
// Add centre point to transform object
function ensureCentre(o, target) {
o.cx = o.cx == null ? target.bbox().cx : o.cx
o.cy = o.cy == null ? target.bbox().cy : o.cy
}
// PathArray Helpers
function arrayToString(a) {
for (var i = 0, il = a.length, s = ''; i < il; i++) {
s += a[i][0]
if (a[i][1] != null) {
s += a[i][1]
if (a[i][2] != null) {
s += ' '
s += a[i][2]
if (a[i][3] != null) {
s += ' '
s += a[i][3]
s += ' '
s += a[i][4]
if (a[i][5] != null) {
s += ' '
s += a[i][5]
s += ' '
s += a[i][6]
if (a[i][7] != null) {
s += ' '
s += a[i][7]
}
}
}
}
}
}
return s + ' '
}
// Deep new id assignment
function assignNewId(node) {
// do the same for SVG child nodes as well
for (var i = node.childNodes.length - 1; i >= 0; i--)
if (node.childNodes[i] instanceof window.SVGElement)
assignNewId(node.childNodes[i])
return SVG.adopt(node).id(SVG.eid(node.nodeName))
}
// Add more bounding box properties
function fullBox(b) {
if (b.x == null) {
b.x = 0
b.y = 0
b.width = 0
b.height = 0
}
b.w = b.width
b.h = b.height
b.x2 = b.x + b.width
b.y2 = b.y + b.height
b.cx = b.x + b.width / 2
b.cy = b.y + b.height / 2
return b
}
// Get id from reference string
function idFromReference(url) {
var m = url.toString().match(SVG.regex.reference)
if (m) return m[1]
}
// Create matrix array for looping
var abcdef = 'abcdef'.split('')
// Add CustomEvent to IE9 and IE10
if (typeof window.CustomEvent !== 'function') {
// Code from: https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent
var CustomEvent = function(event, options) {
options = options || { bubbles: false, cancelable: false, detail: undefined }
var e = document.createEvent('CustomEvent')
e.initCustomEvent(event, options.bubbles, options.cancelable, options.detail)
return e
}
CustomEvent.prototype = window.Event.prototype
window.CustomEvent = CustomEvent
}
// requestAnimationFrame / cancelAnimationFrame Polyfill with fallback based on Paul Irish
(function(w) {
var lastTime = 0
var vendors = ['moz', 'webkit']
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
w.requestAnimationFrame = w[vendors[x] + 'RequestAnimationFrame']
w.cancelAnimationFrame = w[vendors[x] + 'CancelAnimationFrame'] ||
w[vendors[x] + 'CancelRequestAnimationFrame']
}
w.requestAnimationFrame = w.requestAnimationFrame ||
function(callback) {
var currTime = new Date().getTime()
var timeToCall = Math.max(0, 16 - (currTime - lastTime))
var id = w.setTimeout(function() {
callback(currTime + timeToCall)
}, timeToCall)
lastTime = currTime + timeToCall
return id
}
w.cancelAnimationFrame = w.cancelAnimationFrame || w.clearTimeout;
}(window))
return SVG
}));
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| boot.js | 6.67% | (3 / 45) | 0% | (0 / 6) | 7.69% | (1 / 13) | 6.82% | (3 / 44) | |
| console.js | 14.44% | (13 / 90) | 9.38% | (3 / 32) | 5.56% | (1 / 18) | 14.44% | (13 / 90) | |
| jasmine-html.js | 8.1% | (17 / 210) | 0% | (0 / 91) | 0% | (0 / 42) | 8.13% | (17 / 209) | |
| jasmine.js | 9.69% | (174 / 1795) | 1.17% | (9 / 772) | 0.41% | (2 / 482) | 9.85% | (174 / 1767) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 | 2 2 1 | /**
Starting with version 2.0, this file "boots" Jasmine, performing all of the necessary initialization before executing the loaded environment and all of a project's specs. This file should be loaded after `jasmine.js` and `jasmine_html.js`, but before any project source files or spec files are loaded. Thus this file can also be used to customize Jasmine for a project.
If a project is using Jasmine via the standalone distribution, this file can be customized directly. If a project is using Jasmine via the [Ruby gem][jasmine-gem], this file can be copied into the support directory via `jasmine copy_boot_js`. Other environments (e.g., Python) will have different mechanisms.
The location of `boot.js` can be specified and/or overridden in `jasmine.yml`.
[jasmine-gem]: http://github.com/pivotal/jasmine-gem
*/
(function() {
/**
* ## Require & Instantiate
*
* Require Jasmine's core files. Specifically, this requires and attaches all of Jasmine's code to the `jasmine` reference.
*/
window.jasmine = jasmineRequire.core(jasmineRequire);
/**
* Since this is being run in a browser and the results should populate to an HTML page, require the HTML-specific Jasmine code, injecting the same reference.
*/
jasmineRequire.html(jasmine);
/**
* Create the Jasmine environment. This is used to run all specs in a project.
*/
var env = jasmine.getEnv();
/**
* ## The Global Interface
*
* Build up the functions that will be exposed as the Jasmine public interface. A project can customize, rename or alias any of these functions as desired, provided the implementation remains unchanged.
*/
var jasmineInterface = jasmineRequire.interface(jasmine, env);
/**
* Add all of the Jasmine global/public interface to the global scope, so a project can use the public interface directly. For example, calling `describe` in specs instead of `jasmine.getEnv().describe`.
*/
extend(window, jasmineInterface);
/**
* ## Runner Parameters
*
* More browser specific code - wrap the query string in an object and to allow for getting/setting parameters from the runner user interface.
*/
var queryString = new jasmine.QueryString({
getWindowLocation: function() { return window.location; }
});
var catchingExceptions = queryString.getParam("catch");
env.catchExceptions(typeof catchingExceptions === "undefined" ? true : catchingExceptions);
var throwingExpectationFailures = queryString.getParam("throwFailures");
env.throwOnExpectationFailure(throwingExpectationFailures);
var random = queryString.getParam("random");
env.randomizeTests(random);
var seed = queryString.getParam("seed");
if (seed) {
env.seed(seed);
}
/**
* ## Reporters
* The `HtmlReporter` builds all of the HTML UI for the runner page. This reporter paints the dots, stars, and x's for specs, as well as all spec names and all failures (if any).
*/
var htmlReporter = new jasmine.HtmlReporter({
env: env,
onRaiseExceptionsClick: function() { queryString.navigateWithNewParam("catch", !env.catchingExceptions()); },
onThrowExpectationsClick: function() { queryString.navigateWithNewParam("throwFailures", !env.throwingExpectationFailures()); },
onRandomClick: function() { queryString.navigateWithNewParam("random", !env.randomTests()); },
addToExistingQueryString: function(key, value) { return queryString.fullStringWithNewParam(key, value); },
getContainer: function() { return document.body; },
createElement: function() { return document.createElement.apply(document, arguments); },
createTextNode: function() { return document.createTextNode.apply(document, arguments); },
timer: new jasmine.Timer()
});
/**
* The `jsApiReporter` also receives spec results, and is used by any environment that needs to extract the results from JavaScript.
*/
env.addReporter(jasmineInterface.jsApiReporter);
env.addReporter(htmlReporter);
/**
* Filter which specs will be run by matching the start of the full name against the `spec` query param.
*/
var specFilter = new jasmine.HtmlSpecFilter({
filterString: function() { return queryString.getParam("spec"); }
});
env.specFilter = function(spec) {
return specFilter.matches(spec.getFullName());
};
/**
* Setting up timing functions to be able to be overridden. Certain browsers (Safari, IE 8, phantomjs) require this hack.
*/
window.setTimeout = window.setTimeout;
window.setInterval = window.setInterval;
window.clearTimeout = window.clearTimeout;
window.clearInterval = window.clearInterval;
/**
* ## Execution
*
* Replace the browser window's `onload`, ensure it's called, and then run all of the loaded specs. This includes initializing the `HtmlReporter` instance and then executing the loaded Jasmine environment. All of this will happen after all of the specs are loaded.
*/
var currentWindowOnload = window.onload;
window.onload = function() {
if (currentWindowOnload) {
currentWindowOnload();
}
htmlReporter.initialize();
env.execute();
};
/**
* Helper function for readability above.
*/
function extend(destination, source) {
for (var property in source) destination[property] = source[property];
return destination;
}
}());
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 | 1 2 2 1 1 1 1 1 1 1 1 1 1 | /*
Copyright (c) 2008-2016 Pivotal Labs
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
function getJasmineRequireObj() {
Eif (typeof module !== 'undefined' && module.exports) {
return exports;
} else {
window.jasmineRequire = window.jasmineRequire || {};
return window.jasmineRequire;
}
}
getJasmineRequireObj().console = function(jRequire, j$) {
j$.ConsoleReporter = jRequire.ConsoleReporter();
};
getJasmineRequireObj().ConsoleReporter = function() {
var noopTimer = {
start: function(){},
elapsed: function(){ return 0; }
};
function ConsoleReporter(options) {
var print = options.print,
showColors = options.showColors || false,
onComplete = options.onComplete || function() {},
timer = options.timer || noopTimer,
specCount,
failureCount,
failedSpecs = [],
pendingCount,
ansi = {
green: '\x1B[32m',
red: '\x1B[31m',
yellow: '\x1B[33m',
none: '\x1B[0m'
},
failedSuites = [];
print('ConsoleReporter is deprecated and will be removed in a future version.');
this.jasmineStarted = function() {
specCount = 0;
failureCount = 0;
pendingCount = 0;
print('Started');
printNewline();
timer.start();
};
this.jasmineDone = function() {
printNewline();
for (var i = 0; i < failedSpecs.length; i++) {
specFailureDetails(failedSpecs[i]);
}
if(specCount > 0) {
printNewline();
var specCounts = specCount + ' ' + plural('spec', specCount) + ', ' +
failureCount + ' ' + plural('failure', failureCount);
if (pendingCount) {
specCounts += ', ' + pendingCount + ' pending ' + plural('spec', pendingCount);
}
print(specCounts);
} else {
print('No specs found');
}
printNewline();
var seconds = timer.elapsed() / 1000;
print('Finished in ' + seconds + ' ' + plural('second', seconds));
printNewline();
for(i = 0; i < failedSuites.length; i++) {
suiteFailureDetails(failedSuites[i]);
}
onComplete(failureCount === 0);
};
this.specDone = function(result) {
specCount++;
if (result.status == 'pending') {
pendingCount++;
print(colored('yellow', '*'));
return;
}
if (result.status == 'passed') {
print(colored('green', '.'));
return;
}
if (result.status == 'failed') {
failureCount++;
failedSpecs.push(result);
print(colored('red', 'F'));
}
};
this.suiteDone = function(result) {
if (result.failedExpectations && result.failedExpectations.length > 0) {
failureCount++;
failedSuites.push(result);
}
};
return this;
function printNewline() {
print('\n');
}
function colored(color, str) {
return showColors ? (ansi[color] + str + ansi.none) : str;
}
function plural(str, count) {
return count == 1 ? str : str + 's';
}
function repeat(thing, times) {
var arr = [];
for (var i = 0; i < times; i++) {
arr.push(thing);
}
return arr;
}
function indent(str, spaces) {
var lines = (str || '').split('\n');
var newArr = [];
for (var i = 0; i < lines.length; i++) {
newArr.push(repeat(' ', spaces).join('') + lines[i]);
}
return newArr.join('\n');
}
function specFailureDetails(result) {
printNewline();
print(result.fullName);
for (var i = 0; i < result.failedExpectations.length; i++) {
var failedExpectation = result.failedExpectations[i];
printNewline();
print(indent(failedExpectation.message, 2));
print(indent(failedExpectation.stack, 2));
}
printNewline();
}
function suiteFailureDetails(result) {
for (var i = 0; i < result.failedExpectations.length; i++) {
printNewline();
print(colored('red', 'An error was thrown in an afterAll'));
printNewline();
print(colored('red', 'AfterAll ' + result.failedExpectations[i].message));
}
printNewline();
}
}
return ConsoleReporter;
};
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 | 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | /* Copyright (c) 2008-2016 Pivotal Labs Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ jasmineRequire.html = function(j$) { j$.ResultsNode = jasmineRequire.ResultsNode(); j$.HtmlReporter = jasmineRequire.HtmlReporter(j$); j$.QueryString = jasmineRequire.QueryString(); j$.HtmlSpecFilter = jasmineRequire.HtmlSpecFilter(); }; jasmineRequire.HtmlReporter = function(j$) { var noopTimer = { start: function() {}, elapsed: function() { return 0; } }; function HtmlReporter(options) { var env = options.env || {}, getContainer = options.getContainer, createElement = options.createElement, createTextNode = options.createTextNode, onRaiseExceptionsClick = options.onRaiseExceptionsClick || function() {}, onThrowExpectationsClick = options.onThrowExpectationsClick || function() {}, onRandomClick = options.onRandomClick || function() {}, addToExistingQueryString = options.addToExistingQueryString || defaultQueryString, timer = options.timer || noopTimer, results = [], specsExecuted = 0, failureCount = 0, pendingSpecCount = 0, htmlReporterMain, symbols, failedSuites = []; this.initialize = function() { clearPrior(); htmlReporterMain = createDom('div', {className: 'jasmine_html-reporter'}, createDom('div', {className: 'jasmine-banner'}, createDom('a', {className: 'jasmine-title', href: 'http://jasmine.github.io/', target: '_blank'}), createDom('span', {className: 'jasmine-version'}, j$.version) ), createDom('ul', {className: 'jasmine-symbol-summary'}), createDom('div', {className: 'jasmine-alert'}), createDom('div', {className: 'jasmine-results'}, createDom('div', {className: 'jasmine-failures'}) ) ); getContainer().appendChild(htmlReporterMain); }; var totalSpecsDefined; this.jasmineStarted = function(options) { totalSpecsDefined = options.totalSpecsDefined || 0; timer.start(); }; var summary = createDom('div', {className: 'jasmine-summary'}); var topResults = new j$.ResultsNode({}, '', null), currentParent = topResults; this.suiteStarted = function(result) { currentParent.addChild(result, 'suite'); currentParent = currentParent.last(); }; this.suiteDone = function(result) { if (result.status == 'failed') { failedSuites.push(result); } if (currentParent == topResults) { return; } currentParent = currentParent.parent; }; this.specStarted = function(result) { currentParent.addChild(result, 'spec'); }; var failures = []; this.specDone = function(result) { if(noExpectations(result) && typeof console !== 'undefined' && typeof console.error !== 'undefined') { console.error('Spec \'' + result.fullName + '\' has no expectations.'); } if (result.status != 'disabled') { specsExecuted++; } if (!symbols){ symbols = find('.jasmine-symbol-summary'); } symbols.appendChild(createDom('li', { className: noExpectations(result) ? 'jasmine-empty' : 'jasmine-' + result.status, id: 'spec_' + result.id, title: result.fullName } )); if (result.status == 'failed') { failureCount++; var failure = createDom('div', {className: 'jasmine-spec-detail jasmine-failed'}, createDom('div', {className: 'jasmine-description'}, createDom('a', {title: result.fullName, href: specHref(result)}, result.fullName) ), createDom('div', {className: 'jasmine-messages'}) ); var messages = failure.childNodes[1]; for (var i = 0; i < result.failedExpectations.length; i++) { var expectation = result.failedExpectations[i]; messages.appendChild(createDom('div', {className: 'jasmine-result-message'}, expectation.message)); messages.appendChild(createDom('div', {className: 'jasmine-stack-trace'}, expectation.stack)); } failures.push(failure); } if (result.status == 'pending') { pendingSpecCount++; } }; this.jasmineDone = function(doneResult) { var banner = find('.jasmine-banner'); var alert = find('.jasmine-alert'); var order = doneResult && doneResult.order; alert.appendChild(createDom('span', {className: 'jasmine-duration'}, 'finished in ' + timer.elapsed() / 1000 + 's')); banner.appendChild( createDom('div', { className: 'jasmine-run-options' }, createDom('span', { className: 'jasmine-trigger' }, 'Options'), createDom('div', { className: 'jasmine-payload' }, createDom('div', { className: 'jasmine-exceptions' }, createDom('input', { className: 'jasmine-raise', id: 'jasmine-raise-exceptions', type: 'checkbox' }), createDom('label', { className: 'jasmine-label', 'for': 'jasmine-raise-exceptions' }, 'raise exceptions')), createDom('div', { className: 'jasmine-throw-failures' }, createDom('input', { className: 'jasmine-throw', id: 'jasmine-throw-failures', type: 'checkbox' }), createDom('label', { className: 'jasmine-label', 'for': 'jasmine-throw-failures' }, 'stop spec on expectation failure')), createDom('div', { className: 'jasmine-random-order' }, createDom('input', { className: 'jasmine-random', id: 'jasmine-random-order', type: 'checkbox' }), createDom('label', { className: 'jasmine-label', 'for': 'jasmine-random-order' }, 'run tests in random order')) ) )); var raiseCheckbox = find('#jasmine-raise-exceptions'); raiseCheckbox.checked = !env.catchingExceptions(); raiseCheckbox.onclick = onRaiseExceptionsClick; var throwCheckbox = find('#jasmine-throw-failures'); throwCheckbox.checked = env.throwingExpectationFailures(); throwCheckbox.onclick = onThrowExpectationsClick; var randomCheckbox = find('#jasmine-random-order'); randomCheckbox.checked = env.randomTests(); randomCheckbox.onclick = onRandomClick; var optionsMenu = find('.jasmine-run-options'), optionsTrigger = optionsMenu.querySelector('.jasmine-trigger'), optionsPayload = optionsMenu.querySelector('.jasmine-payload'), isOpen = /\bjasmine-open\b/; optionsTrigger.onclick = function() { if (isOpen.test(optionsPayload.className)) { optionsPayload.className = optionsPayload.className.replace(isOpen, ''); } else { optionsPayload.className += ' jasmine-open'; } }; if (specsExecuted < totalSpecsDefined) { var skippedMessage = 'Ran ' + specsExecuted + ' of ' + totalSpecsDefined + ' specs - run all'; var skippedLink = order && order.random ? '?random=true' : '?'; alert.appendChild( createDom('span', {className: 'jasmine-bar jasmine-skipped'}, createDom('a', {href: skippedLink, title: 'Run all specs'}, skippedMessage) ) ); } var statusBarMessage = ''; var statusBarClassName = 'jasmine-bar '; if (totalSpecsDefined > 0) { statusBarMessage += pluralize('spec', specsExecuted) + ', ' + pluralize('failure', failureCount); if (pendingSpecCount) { statusBarMessage += ', ' + pluralize('pending spec', pendingSpecCount); } statusBarClassName += (failureCount > 0) ? 'jasmine-failed' : 'jasmine-passed'; } else { statusBarClassName += 'jasmine-skipped'; statusBarMessage += 'No specs found'; } var seedBar; if (order && order.random) { seedBar = createDom('span', {className: 'jasmine-seed-bar'}, ', randomized with seed ', createDom('a', {title: 'randomized with seed ' + order.seed, href: seedHref(order.seed)}, order.seed) ); } alert.appendChild(createDom('span', {className: statusBarClassName}, statusBarMessage, seedBar)); var errorBarClassName = 'jasmine-bar jasmine-errored'; var errorBarMessagePrefix = 'AfterAll '; for(var i = 0; i < failedSuites.length; i++) { var failedSuite = failedSuites[i]; for(var j = 0; j < failedSuite.failedExpectations.length; j++) { alert.appendChild(createDom('span', {className: errorBarClassName}, errorBarMessagePrefix + failedSuite.failedExpectations[j].message)); } } var globalFailures = (doneResult && doneResult.failedExpectations) || []; for(i = 0; i < globalFailures.length; i++) { var failure = globalFailures[i]; alert.appendChild(createDom('span', {className: errorBarClassName}, errorBarMessagePrefix + failure.message)); } var results = find('.jasmine-results'); results.appendChild(summary); summaryList(topResults, summary); function summaryList(resultsTree, domParent) { var specListNode; for (var i = 0; i < resultsTree.children.length; i++) { var resultNode = resultsTree.children[i]; if (resultNode.type == 'suite') { var suiteListNode = createDom('ul', {className: 'jasmine-suite', id: 'suite-' + resultNode.result.id}, createDom('li', {className: 'jasmine-suite-detail'}, createDom('a', {href: specHref(resultNode.result)}, resultNode.result.description) ) ); summaryList(resultNode, suiteListNode); domParent.appendChild(suiteListNode); } if (resultNode.type == 'spec') { if (domParent.getAttribute('class') != 'jasmine-specs') { specListNode = createDom('ul', {className: 'jasmine-specs'}); domParent.appendChild(specListNode); } var specDescription = resultNode.result.description; if(noExpectations(resultNode.result)) { specDescription = 'SPEC HAS NO EXPECTATIONS ' + specDescription; } if(resultNode.result.status === 'pending' && resultNode.result.pendingReason !== '') { specDescription = specDescription + ' PENDING WITH MESSAGE: ' + resultNode.result.pendingReason; } specListNode.appendChild( createDom('li', { className: 'jasmine-' + resultNode.result.status, id: 'spec-' + resultNode.result.id }, createDom('a', {href: specHref(resultNode.result)}, specDescription) ) ); } } } if (failures.length) { alert.appendChild( createDom('span', {className: 'jasmine-menu jasmine-bar jasmine-spec-list'}, createDom('span', {}, 'Spec List | '), createDom('a', {className: 'jasmine-failures-menu', href: '#'}, 'Failures'))); alert.appendChild( createDom('span', {className: 'jasmine-menu jasmine-bar jasmine-failure-list'}, createDom('a', {className: 'jasmine-spec-list-menu', href: '#'}, 'Spec List'), createDom('span', {}, ' | Failures '))); find('.jasmine-failures-menu').onclick = function() { setMenuModeTo('jasmine-failure-list'); }; find('.jasmine-spec-list-menu').onclick = function() { setMenuModeTo('jasmine-spec-list'); }; setMenuModeTo('jasmine-failure-list'); var failureNode = find('.jasmine-failures'); for (i = 0; i < failures.length; i++) { failureNode.appendChild(failures[i]); } } }; return this; function find(selector) { return getContainer().querySelector('.jasmine_html-reporter ' + selector); } function clearPrior() { // return the reporter var oldReporter = find(''); if(oldReporter) { getContainer().removeChild(oldReporter); } } function createDom(type, attrs, childrenVarArgs) { var el = createElement(type); for (var i = 2; i < arguments.length; i++) { var child = arguments[i]; if (typeof child === 'string') { el.appendChild(createTextNode(child)); } else { if (child) { el.appendChild(child); } } } for (var attr in attrs) { if (attr == 'className') { el[attr] = attrs[attr]; } else { el.setAttribute(attr, attrs[attr]); } } return el; } function pluralize(singular, count) { var word = (count == 1 ? singular : singular + 's'); return '' + count + ' ' + word; } function specHref(result) { return addToExistingQueryString('spec', result.fullName); } function seedHref(seed) { return addToExistingQueryString('seed', seed); } function defaultQueryString(key, value) { return '?' + key + '=' + value; } function setMenuModeTo(mode) { htmlReporterMain.setAttribute('class', 'jasmine_html-reporter ' + mode); } function noExpectations(result) { return (result.failedExpectations.length + result.passedExpectations.length) === 0 && result.status === 'passed'; } } return HtmlReporter; }; jasmineRequire.HtmlSpecFilter = function() { function HtmlSpecFilter(options) { var filterString = options && options.filterString() && options.filterString().replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); var filterPattern = new RegExp(filterString); this.matches = function(specName) { return filterPattern.test(specName); }; } return HtmlSpecFilter; }; jasmineRequire.ResultsNode = function() { function ResultsNode(result, type, parent) { this.result = result; this.type = type; this.parent = parent; this.children = []; this.addChild = function(result, type) { this.children.push(new ResultsNode(result, type, this)); }; this.last = function() { return this.children[this.children.length - 1]; }; } return ResultsNode; }; jasmineRequire.QueryString = function() { function QueryString(options) { this.navigateWithNewParam = function(key, value) { options.getWindowLocation().search = this.fullStringWithNewParam(key, value); }; this.fullStringWithNewParam = function(key, value) { var paramMap = queryStringToParamMap(); paramMap[key] = value; return toQueryString(paramMap); }; this.getParam = function(key) { return queryStringToParamMap()[key]; }; return this; function toQueryString(paramMap) { var qStrPairs = []; for (var prop in paramMap) { qStrPairs.push(encodeURIComponent(prop) + '=' + encodeURIComponent(paramMap[prop])); } return '?' + qStrPairs.join('&'); } function queryStringToParamMap() { var paramStr = options.getWindowLocation().search.substring(1), params = [], paramMap = {}; if (paramStr.length > 0) { params = paramStr.split('&'); for (var i = 0; i < params.length; i++) { var p = params[i].split('='); var value = decodeURIComponent(p[1]); if (value === 'true' || value === 'false') { value = JSON.parse(value); } paramMap[decodeURIComponent(p[0])] = value; } } return paramMap; } } return QueryString; }; |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 | 1 1 1 1 1 1 1 53 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | /*
Copyright (c) 2008-2016 Pivotal Labs
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
var getJasmineRequireObj = (function (jasmineGlobal) {
var jasmineRequire;
Eif (typeof module !== 'undefined' && module.exports && typeof exports !== 'undefined') {
Eif (typeof global !== 'undefined') {
jasmineGlobal = global;
} else {
jasmineGlobal = {};
}
jasmineRequire = exports;
} else {
if (typeof window !== 'undefined' && typeof window.toString === 'function' && window.toString() === '[object GjsGlobal]') {
jasmineGlobal = window;
}
jasmineRequire = jasmineGlobal.jasmineRequire = jasmineGlobal.jasmineRequire || {};
}
function getJasmineRequire() {
return jasmineRequire;
}
getJasmineRequire().core = function(jRequire) {
var j$ = {};
jRequire.base(j$, jasmineGlobal);
j$.util = jRequire.util();
j$.errors = jRequire.errors();
j$.formatErrorMsg = jRequire.formatErrorMsg();
j$.Any = jRequire.Any(j$);
j$.Anything = jRequire.Anything(j$);
j$.CallTracker = jRequire.CallTracker(j$);
j$.MockDate = jRequire.MockDate();
j$.Clock = jRequire.Clock();
j$.DelayedFunctionScheduler = jRequire.DelayedFunctionScheduler();
j$.Env = jRequire.Env(j$);
j$.ExceptionFormatter = jRequire.ExceptionFormatter();
j$.Expectation = jRequire.Expectation();
j$.buildExpectationResult = jRequire.buildExpectationResult();
j$.JsApiReporter = jRequire.JsApiReporter();
j$.matchersUtil = jRequire.matchersUtil(j$);
j$.ObjectContaining = jRequire.ObjectContaining(j$);
j$.ArrayContaining = jRequire.ArrayContaining(j$);
j$.pp = jRequire.pp(j$);
j$.QueueRunner = jRequire.QueueRunner(j$);
j$.ReportDispatcher = jRequire.ReportDispatcher();
j$.Spec = jRequire.Spec(j$);
j$.SpyRegistry = jRequire.SpyRegistry(j$);
j$.SpyStrategy = jRequire.SpyStrategy(j$);
j$.StringMatching = jRequire.StringMatching(j$);
j$.Suite = jRequire.Suite(j$);
j$.Timer = jRequire.Timer();
j$.TreeProcessor = jRequire.TreeProcessor();
j$.version = jRequire.version();
j$.Order = jRequire.Order();
j$.matchers = jRequire.requireMatchers(jRequire, j$);
return j$;
};
return getJasmineRequire;
})(this);
getJasmineRequireObj().requireMatchers = function(jRequire, j$) {
var availableMatchers = [
'toBe',
'toBeCloseTo',
'toBeDefined',
'toBeFalsy',
'toBeGreaterThan',
'toBeGreaterThanOrEqual',
'toBeLessThanOrEqual',
'toBeLessThan',
'toBeNaN',
'toBeNull',
'toBeTruthy',
'toBeUndefined',
'toContain',
'toEqual',
'toHaveBeenCalled',
'toHaveBeenCalledWith',
'toHaveBeenCalledTimes',
'toMatch',
'toThrow',
'toThrowError'
],
matchers = {};
for (var i = 0; i < availableMatchers.length; i++) {
var name = availableMatchers[i];
matchers[name] = jRequire[name](j$);
}
return matchers;
};
getJasmineRequireObj().base = function(j$, jasmineGlobal) {
j$.unimplementedMethod_ = function() {
throw new Error('unimplemented method');
};
j$.MAX_PRETTY_PRINT_DEPTH = 40;
j$.MAX_PRETTY_PRINT_ARRAY_LENGTH = 100;
j$.DEFAULT_TIMEOUT_INTERVAL = 5000;
j$.getGlobal = function() {
return jasmineGlobal;
};
j$.getEnv = function(options) {
var env = j$.currentEnv_ = j$.currentEnv_ || new j$.Env(options);
//jasmine. singletons in here (setTimeout blah blah).
return env;
};
j$.isArray_ = function(value) {
return j$.isA_('Array', value);
};
j$.isString_ = function(value) {
return j$.isA_('String', value);
};
j$.isNumber_ = function(value) {
return j$.isA_('Number', value);
};
j$.isFunction_ = function(value) {
return j$.isA_('Function', value);
};
j$.isA_ = function(typeName, value) {
return Object.prototype.toString.apply(value) === '[object ' + typeName + ']';
};
j$.isDomNode = function(obj) {
return obj.nodeType > 0;
};
j$.fnNameFor = function(func) {
if (func.name) {
return func.name;
}
var matches = func.toString().match(/^\s*function\s*(\w*)\s*\(/);
return matches ? matches[1] : '<anonymous>';
};
j$.any = function(clazz) {
return new j$.Any(clazz);
};
j$.anything = function() {
return new j$.Anything();
};
j$.objectContaining = function(sample) {
return new j$.ObjectContaining(sample);
};
j$.stringMatching = function(expected) {
return new j$.StringMatching(expected);
};
j$.arrayContaining = function(sample) {
return new j$.ArrayContaining(sample);
};
j$.createSpy = function(name, originalFn) {
var spyStrategy = new j$.SpyStrategy({
name: name,
fn: originalFn,
getSpy: function() { return spy; }
}),
callTracker = new j$.CallTracker(),
spy = function() {
var callData = {
object: this,
args: Array.prototype.slice.apply(arguments)
};
callTracker.track(callData);
var returnValue = spyStrategy.exec.apply(this, arguments);
callData.returnValue = returnValue;
return returnValue;
};
for (var prop in originalFn) {
if (prop === 'and' || prop === 'calls') {
throw new Error('Jasmine spies would overwrite the \'and\' and \'calls\' properties on the object being spied upon');
}
spy[prop] = originalFn[prop];
}
spy.and = spyStrategy;
spy.calls = callTracker;
return spy;
};
j$.isSpy = function(putativeSpy) {
if (!putativeSpy) {
return false;
}
return putativeSpy.and instanceof j$.SpyStrategy &&
putativeSpy.calls instanceof j$.CallTracker;
};
j$.createSpyObj = function(baseName, methodNames) {
if (j$.isArray_(baseName) && j$.util.isUndefined(methodNames)) {
methodNames = baseName;
baseName = 'unknown';
}
if (!j$.isArray_(methodNames) || methodNames.length === 0) {
throw 'createSpyObj requires a non-empty array of method names to create spies for';
}
var obj = {};
for (var i = 0; i < methodNames.length; i++) {
obj[methodNames[i]] = j$.createSpy(baseName + '.' + methodNames[i]);
}
return obj;
};
};
getJasmineRequireObj().util = function() {
var util = {};
util.inherit = function(childClass, parentClass) {
var Subclass = function() {
};
Subclass.prototype = parentClass.prototype;
childClass.prototype = new Subclass();
};
util.htmlEscape = function(str) {
if (!str) {
return str;
}
return str.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>');
};
util.argsToArray = function(args) {
var arrayOfArgs = [];
for (var i = 0; i < args.length; i++) {
arrayOfArgs.push(args[i]);
}
return arrayOfArgs;
};
util.isUndefined = function(obj) {
return obj === void 0;
};
util.arrayContains = function(array, search) {
var i = array.length;
while (i--) {
if (array[i] === search) {
return true;
}
}
return false;
};
util.clone = function(obj) {
if (Object.prototype.toString.apply(obj) === '[object Array]') {
return obj.slice();
}
var cloned = {};
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
cloned[prop] = obj[prop];
}
}
return cloned;
};
return util;
};
getJasmineRequireObj().Spec = function(j$) {
function Spec(attrs) {
this.expectationFactory = attrs.expectationFactory;
this.resultCallback = attrs.resultCallback || function() {};
this.id = attrs.id;
this.description = attrs.description || '';
this.queueableFn = attrs.queueableFn;
this.beforeAndAfterFns = attrs.beforeAndAfterFns || function() { return {befores: [], afters: []}; };
this.userContext = attrs.userContext || function() { return {}; };
this.onStart = attrs.onStart || function() {};
this.getSpecName = attrs.getSpecName || function() { return ''; };
this.expectationResultFactory = attrs.expectationResultFactory || function() { };
this.queueRunnerFactory = attrs.queueRunnerFactory || function() {};
this.catchingExceptions = attrs.catchingExceptions || function() { return true; };
this.throwOnExpectationFailure = !!attrs.throwOnExpectationFailure;
if (!this.queueableFn.fn) {
this.pend();
}
this.result = {
id: this.id,
description: this.description,
fullName: this.getFullName(),
failedExpectations: [],
passedExpectations: [],
pendingReason: ''
};
}
Spec.prototype.addExpectationResult = function(passed, data, isError) {
var expectationResult = this.expectationResultFactory(data);
if (passed) {
this.result.passedExpectations.push(expectationResult);
} else {
this.result.failedExpectations.push(expectationResult);
if (this.throwOnExpectationFailure && !isError) {
throw new j$.errors.ExpectationFailed();
}
}
};
Spec.prototype.expect = function(actual) {
return this.expectationFactory(actual, this);
};
Spec.prototype.execute = function(onComplete, enabled) {
var self = this;
this.onStart(this);
if (!this.isExecutable() || this.markedPending || enabled === false) {
complete(enabled);
return;
}
var fns = this.beforeAndAfterFns();
var allFns = fns.befores.concat(this.queueableFn).concat(fns.afters);
this.queueRunnerFactory({
queueableFns: allFns,
onException: function() { self.onException.apply(self, arguments); },
onComplete: complete,
userContext: this.userContext()
});
function complete(enabledAgain) {
self.result.status = self.status(enabledAgain);
self.resultCallback(self.result);
if (onComplete) {
onComplete();
}
}
};
Spec.prototype.onException = function onException(e) {
if (Spec.isPendingSpecException(e)) {
this.pend(extractCustomPendingMessage(e));
return;
}
if (e instanceof j$.errors.ExpectationFailed) {
return;
}
this.addExpectationResult(false, {
matcherName: '',
passed: false,
expected: '',
actual: '',
error: e
}, true);
};
Spec.prototype.disable = function() {
this.disabled = true;
};
Spec.prototype.pend = function(message) {
this.markedPending = true;
if (message) {
this.result.pendingReason = message;
}
};
Spec.prototype.getResult = function() {
this.result.status = this.status();
return this.result;
};
Spec.prototype.status = function(enabled) {
if (this.disabled || enabled === false) {
return 'disabled';
}
if (this.markedPending) {
return 'pending';
}
if (this.result.failedExpectations.length > 0) {
return 'failed';
} else {
return 'passed';
}
};
Spec.prototype.isExecutable = function() {
return !this.disabled;
};
Spec.prototype.getFullName = function() {
return this.getSpecName(this);
};
var extractCustomPendingMessage = function(e) {
var fullMessage = e.toString(),
boilerplateStart = fullMessage.indexOf(Spec.pendingSpecExceptionMessage),
boilerplateEnd = boilerplateStart + Spec.pendingSpecExceptionMessage.length;
return fullMessage.substr(boilerplateEnd);
};
Spec.pendingSpecExceptionMessage = '=> marked Pending';
Spec.isPendingSpecException = function(e) {
return !!(e && e.toString && e.toString().indexOf(Spec.pendingSpecExceptionMessage) !== -1);
};
return Spec;
};
Iif (typeof window == void 0 && typeof exports == 'object') {
exports.Spec = jasmineRequire.Spec;
}
/*jshint bitwise: false*/
getJasmineRequireObj().Order = function() {
function Order(options) {
this.random = 'random' in options ? options.random : true;
var seed = this.seed = options.seed || generateSeed();
this.sort = this.random ? randomOrder : naturalOrder;
function naturalOrder(items) {
return items;
}
function randomOrder(items) {
var copy = items.slice();
copy.sort(function(a, b) {
return jenkinsHash(seed + a.id) - jenkinsHash(seed + b.id);
});
return copy;
}
function generateSeed() {
return String(Math.random()).slice(-5);
}
// Bob Jenkins One-at-a-Time Hash algorithm is a non-cryptographic hash function
// used to get a different output when the key changes slighly.
// We use your return to sort the children randomly in a consistent way when
// used in conjunction with a seed
function jenkinsHash(key) {
var hash, i;
for(hash = i = 0; i < key.length; ++i) {
hash += key.charCodeAt(i);
hash += (hash << 10);
hash ^= (hash >> 6);
}
hash += (hash << 3);
hash ^= (hash >> 11);
hash += (hash << 15);
return hash;
}
}
return Order;
};
getJasmineRequireObj().Env = function(j$) {
function Env(options) {
options = options || {};
var self = this;
var global = options.global || j$.getGlobal();
var totalSpecsDefined = 0;
var catchExceptions = true;
var realSetTimeout = j$.getGlobal().setTimeout;
var realClearTimeout = j$.getGlobal().clearTimeout;
this.clock = new j$.Clock(global, function () { return new j$.DelayedFunctionScheduler(); }, new j$.MockDate(global));
var runnableResources = {};
var currentSpec = null;
var currentlyExecutingSuites = [];
var currentDeclarationSuite = null;
var throwOnExpectationFailure = false;
var random = false;
var seed = null;
var currentSuite = function() {
return currentlyExecutingSuites[currentlyExecutingSuites.length - 1];
};
var currentRunnable = function() {
return currentSpec || currentSuite();
};
var reporter = new j$.ReportDispatcher([
'jasmineStarted',
'jasmineDone',
'suiteStarted',
'suiteDone',
'specStarted',
'specDone'
]);
this.specFilter = function() {
return true;
};
this.addCustomEqualityTester = function(tester) {
if(!currentRunnable()) {
throw new Error('Custom Equalities must be added in a before function or a spec');
}
runnableResources[currentRunnable().id].customEqualityTesters.push(tester);
};
this.addMatchers = function(matchersToAdd) {
if(!currentRunnable()) {
throw new Error('Matchers must be added in a before function or a spec');
}
var customMatchers = runnableResources[currentRunnable().id].customMatchers;
for (var matcherName in matchersToAdd) {
customMatchers[matcherName] = matchersToAdd[matcherName];
}
};
j$.Expectation.addCoreMatchers(j$.matchers);
var nextSpecId = 0;
var getNextSpecId = function() {
return 'spec' + nextSpecId++;
};
var nextSuiteId = 0;
var getNextSuiteId = function() {
return 'suite' + nextSuiteId++;
};
var expectationFactory = function(actual, spec) {
return j$.Expectation.Factory({
util: j$.matchersUtil,
customEqualityTesters: runnableResources[spec.id].customEqualityTesters,
customMatchers: runnableResources[spec.id].customMatchers,
actual: actual,
addExpectationResult: addExpectationResult
});
function addExpectationResult(passed, result) {
return spec.addExpectationResult(passed, result);
}
};
var defaultResourcesForRunnable = function(id, parentRunnableId) {
var resources = {spies: [], customEqualityTesters: [], customMatchers: {}};
if(runnableResources[parentRunnableId]){
resources.customEqualityTesters = j$.util.clone(runnableResources[parentRunnableId].customEqualityTesters);
resources.customMatchers = j$.util.clone(runnableResources[parentRunnableId].customMatchers);
}
runnableResources[id] = resources;
};
var clearResourcesForRunnable = function(id) {
spyRegistry.clearSpies();
delete runnableResources[id];
};
var beforeAndAfterFns = function(suite) {
return function() {
var befores = [],
afters = [];
while(suite) {
befores = befores.concat(suite.beforeFns);
afters = afters.concat(suite.afterFns);
suite = suite.parentSuite;
}
return {
befores: befores.reverse(),
afters: afters
};
};
};
var getSpecName = function(spec, suite) {
var fullName = [spec.description],
suiteFullName = suite.getFullName();
if (suiteFullName !== '') {
fullName.unshift(suiteFullName);
}
return fullName.join(' ');
};
// TODO: we may just be able to pass in the fn instead of wrapping here
var buildExpectationResult = j$.buildExpectationResult,
exceptionFormatter = new j$.ExceptionFormatter(),
expectationResultFactory = function(attrs) {
attrs.messageFormatter = exceptionFormatter.message;
attrs.stackFormatter = exceptionFormatter.stack;
return buildExpectationResult(attrs);
};
// TODO: fix this naming, and here's where the value comes in
this.catchExceptions = function(value) {
catchExceptions = !!value;
return catchExceptions;
};
this.catchingExceptions = function() {
return catchExceptions;
};
var maximumSpecCallbackDepth = 20;
var currentSpecCallbackDepth = 0;
function clearStack(fn) {
currentSpecCallbackDepth++;
if (currentSpecCallbackDepth >= maximumSpecCallbackDepth) {
currentSpecCallbackDepth = 0;
realSetTimeout(fn, 0);
} else {
fn();
}
}
var catchException = function(e) {
return j$.Spec.isPendingSpecException(e) || catchExceptions;
};
this.throwOnExpectationFailure = function(value) {
throwOnExpectationFailure = !!value;
};
this.throwingExpectationFailures = function() {
return throwOnExpectationFailure;
};
this.randomizeTests = function(value) {
random = !!value;
};
this.randomTests = function() {
return random;
};
this.seed = function(value) {
if (value) {
seed = value;
}
return seed;
};
var queueRunnerFactory = function(options) {
options.catchException = catchException;
options.clearStack = options.clearStack || clearStack;
options.timeout = {setTimeout: realSetTimeout, clearTimeout: realClearTimeout};
options.fail = self.fail;
new j$.QueueRunner(options).execute();
};
var topSuite = new j$.Suite({
env: this,
id: getNextSuiteId(),
description: 'Jasmine__TopLevel__Suite',
expectationFactory: expectationFactory,
expectationResultFactory: expectationResultFactory
});
defaultResourcesForRunnable(topSuite.id);
currentDeclarationSuite = topSuite;
this.topSuite = function() {
return topSuite;
};
this.execute = function(runnablesToRun) {
if(!runnablesToRun) {
if (focusedRunnables.length) {
runnablesToRun = focusedRunnables;
} else {
runnablesToRun = [topSuite.id];
}
}
var order = new j$.Order({
random: random,
seed: seed
});
var processor = new j$.TreeProcessor({
tree: topSuite,
runnableIds: runnablesToRun,
queueRunnerFactory: queueRunnerFactory,
nodeStart: function(suite) {
currentlyExecutingSuites.push(suite);
defaultResourcesForRunnable(suite.id, suite.parentSuite.id);
reporter.suiteStarted(suite.result);
},
nodeComplete: function(suite, result) {
if (!suite.disabled) {
clearResourcesForRunnable(suite.id);
}
currentlyExecutingSuites.pop();
reporter.suiteDone(result);
},
orderChildren: function(node) {
return order.sort(node.children);
}
});
if(!processor.processTree().valid) {
throw new Error('Invalid order: would cause a beforeAll or afterAll to be run multiple times');
}
reporter.jasmineStarted({
totalSpecsDefined: totalSpecsDefined
});
currentlyExecutingSuites.push(topSuite);
processor.execute(function() {
clearResourcesForRunnable(topSuite.id);
currentlyExecutingSuites.pop();
reporter.jasmineDone({
order: order,
failedExpectations: topSuite.result.failedExpectations
});
});
};
this.addReporter = function(reporterToAdd) {
reporter.addReporter(reporterToAdd);
};
this.provideFallbackReporter = function(reporterToAdd) {
reporter.provideFallbackReporter(reporterToAdd);
};
this.clearReporters = function() {
reporter.clearReporters();
};
var spyRegistry = new j$.SpyRegistry({currentSpies: function() {
if(!currentRunnable()) {
throw new Error('Spies must be created in a before function or a spec');
}
return runnableResources[currentRunnable().id].spies;
}});
this.allowRespy = function(allow){
spyRegistry.allowRespy(allow);
};
this.spyOn = function() {
return spyRegistry.spyOn.apply(spyRegistry, arguments);
};
var suiteFactory = function(description) {
var suite = new j$.Suite({
env: self,
id: getNextSuiteId(),
description: description,
parentSuite: currentDeclarationSuite,
expectationFactory: expectationFactory,
expectationResultFactory: expectationResultFactory,
throwOnExpectationFailure: throwOnExpectationFailure
});
return suite;
};
this.describe = function(description, specDefinitions) {
var suite = suiteFactory(description);
if (specDefinitions.length > 0) {
throw new Error('describe does not expect any arguments');
}
if (currentDeclarationSuite.markedPending) {
suite.pend();
}
addSpecsToSuite(suite, specDefinitions);
return suite;
};
this.xdescribe = function(description, specDefinitions) {
var suite = suiteFactory(description);
suite.pend();
addSpecsToSuite(suite, specDefinitions);
return suite;
};
var focusedRunnables = [];
this.fdescribe = function(description, specDefinitions) {
var suite = suiteFactory(description);
suite.isFocused = true;
focusedRunnables.push(suite.id);
unfocusAncestor();
addSpecsToSuite(suite, specDefinitions);
return suite;
};
function addSpecsToSuite(suite, specDefinitions) {
var parentSuite = currentDeclarationSuite;
parentSuite.addChild(suite);
currentDeclarationSuite = suite;
var declarationError = null;
try {
specDefinitions.call(suite);
} catch (e) {
declarationError = e;
}
if (declarationError) {
self.it('encountered a declaration exception', function() {
throw declarationError;
});
}
currentDeclarationSuite = parentSuite;
}
function findFocusedAncestor(suite) {
while (suite) {
if (suite.isFocused) {
return suite.id;
}
suite = suite.parentSuite;
}
return null;
}
function unfocusAncestor() {
var focusedAncestor = findFocusedAncestor(currentDeclarationSuite);
if (focusedAncestor) {
for (var i = 0; i < focusedRunnables.length; i++) {
if (focusedRunnables[i] === focusedAncestor) {
focusedRunnables.splice(i, 1);
break;
}
}
}
}
var specFactory = function(description, fn, suite, timeout) {
totalSpecsDefined++;
var spec = new j$.Spec({
id: getNextSpecId(),
beforeAndAfterFns: beforeAndAfterFns(suite),
expectationFactory: expectationFactory,
resultCallback: specResultCallback,
getSpecName: function(spec) {
return getSpecName(spec, suite);
},
onStart: specStarted,
description: description,
expectationResultFactory: expectationResultFactory,
queueRunnerFactory: queueRunnerFactory,
userContext: function() { return suite.clonedSharedUserContext(); },
queueableFn: {
fn: fn,
timeout: function() { return timeout || j$.DEFAULT_TIMEOUT_INTERVAL; }
},
throwOnExpectationFailure: throwOnExpectationFailure
});
if (!self.specFilter(spec)) {
spec.disable();
}
return spec;
function specResultCallback(result) {
clearResourcesForRunnable(spec.id);
currentSpec = null;
reporter.specDone(result);
}
function specStarted(spec) {
currentSpec = spec;
defaultResourcesForRunnable(spec.id, suite.id);
reporter.specStarted(spec.result);
}
};
this.it = function(description, fn, timeout) {
var spec = specFactory(description, fn, currentDeclarationSuite, timeout);
if (currentDeclarationSuite.markedPending) {
spec.pend();
}
currentDeclarationSuite.addChild(spec);
return spec;
};
this.xit = function() {
var spec = this.it.apply(this, arguments);
spec.pend('Temporarily disabled with xit');
return spec;
};
this.fit = function(description, fn, timeout){
var spec = specFactory(description, fn, currentDeclarationSuite, timeout);
currentDeclarationSuite.addChild(spec);
focusedRunnables.push(spec.id);
unfocusAncestor();
return spec;
};
this.expect = function(actual) {
if (!currentRunnable()) {
throw new Error('\'expect\' was used when there was no current spec, this could be because an asynchronous test timed out');
}
return currentRunnable().expect(actual);
};
this.beforeEach = function(beforeEachFunction, timeout) {
currentDeclarationSuite.beforeEach({
fn: beforeEachFunction,
timeout: function() { return timeout || j$.DEFAULT_TIMEOUT_INTERVAL; }
});
};
this.beforeAll = function(beforeAllFunction, timeout) {
currentDeclarationSuite.beforeAll({
fn: beforeAllFunction,
timeout: function() { return timeout || j$.DEFAULT_TIMEOUT_INTERVAL; }
});
};
this.afterEach = function(afterEachFunction, timeout) {
currentDeclarationSuite.afterEach({
fn: afterEachFunction,
timeout: function() { return timeout || j$.DEFAULT_TIMEOUT_INTERVAL; }
});
};
this.afterAll = function(afterAllFunction, timeout) {
currentDeclarationSuite.afterAll({
fn: afterAllFunction,
timeout: function() { return timeout || j$.DEFAULT_TIMEOUT_INTERVAL; }
});
};
this.pending = function(message) {
var fullMessage = j$.Spec.pendingSpecExceptionMessage;
if(message) {
fullMessage += message;
}
throw fullMessage;
};
this.fail = function(error) {
var message = 'Failed';
if (error) {
message += ': ';
message += error.message || error;
}
currentRunnable().addExpectationResult(false, {
matcherName: '',
passed: false,
expected: '',
actual: '',
message: message,
error: error && error.message ? error : null
});
};
}
return Env;
};
getJasmineRequireObj().JsApiReporter = function() {
var noopTimer = {
start: function(){},
elapsed: function(){ return 0; }
};
function JsApiReporter(options) {
var timer = options.timer || noopTimer,
status = 'loaded';
this.started = false;
this.finished = false;
this.runDetails = {};
this.jasmineStarted = function() {
this.started = true;
status = 'started';
timer.start();
};
var executionTime;
this.jasmineDone = function(runDetails) {
this.finished = true;
this.runDetails = runDetails;
executionTime = timer.elapsed();
status = 'done';
};
this.status = function() {
return status;
};
var suites = [],
suites_hash = {};
this.suiteStarted = function(result) {
suites_hash[result.id] = result;
};
this.suiteDone = function(result) {
storeSuite(result);
};
this.suiteResults = function(index, length) {
return suites.slice(index, index + length);
};
function storeSuite(result) {
suites.push(result);
suites_hash[result.id] = result;
}
this.suites = function() {
return suites_hash;
};
var specs = [];
this.specDone = function(result) {
specs.push(result);
};
this.specResults = function(index, length) {
return specs.slice(index, index + length);
};
this.specs = function() {
return specs;
};
this.executionTime = function() {
return executionTime;
};
}
return JsApiReporter;
};
getJasmineRequireObj().CallTracker = function(j$) {
function CallTracker() {
var calls = [];
var opts = {};
function argCloner(context) {
var clonedArgs = [];
var argsAsArray = j$.util.argsToArray(context.args);
for(var i = 0; i < argsAsArray.length; i++) {
if(Object.prototype.toString.apply(argsAsArray[i]).match(/^\[object/)) {
clonedArgs.push(j$.util.clone(argsAsArray[i]));
} else {
clonedArgs.push(argsAsArray[i]);
}
}
context.args = clonedArgs;
}
this.track = function(context) {
if(opts.cloneArgs) {
argCloner(context);
}
calls.push(context);
};
this.any = function() {
return !!calls.length;
};
this.count = function() {
return calls.length;
};
this.argsFor = function(index) {
var call = calls[index];
return call ? call.args : [];
};
this.all = function() {
return calls;
};
this.allArgs = function() {
var callArgs = [];
for(var i = 0; i < calls.length; i++){
callArgs.push(calls[i].args);
}
return callArgs;
};
this.first = function() {
return calls[0];
};
this.mostRecent = function() {
return calls[calls.length - 1];
};
this.reset = function() {
calls = [];
};
this.saveArgumentsByValue = function() {
opts.cloneArgs = true;
};
}
return CallTracker;
};
getJasmineRequireObj().Clock = function() {
function Clock(global, delayedFunctionSchedulerFactory, mockDate) {
var self = this,
realTimingFunctions = {
setTimeout: global.setTimeout,
clearTimeout: global.clearTimeout,
setInterval: global.setInterval,
clearInterval: global.clearInterval
},
fakeTimingFunctions = {
setTimeout: setTimeout,
clearTimeout: clearTimeout,
setInterval: setInterval,
clearInterval: clearInterval
},
installed = false,
delayedFunctionScheduler,
timer;
self.install = function() {
if(!originalTimingFunctionsIntact()) {
throw new Error('Jasmine Clock was unable to install over custom global timer functions. Is the clock already installed?');
}
replace(global, fakeTimingFunctions);
timer = fakeTimingFunctions;
delayedFunctionScheduler = delayedFunctionSchedulerFactory();
installed = true;
return self;
};
self.uninstall = function() {
delayedFunctionScheduler = null;
mockDate.uninstall();
replace(global, realTimingFunctions);
timer = realTimingFunctions;
installed = false;
};
self.withMock = function(closure) {
this.install();
try {
closure();
} finally {
this.uninstall();
}
};
self.mockDate = function(initialDate) {
mockDate.install(initialDate);
};
self.setTimeout = function(fn, delay, params) {
if (legacyIE()) {
if (arguments.length > 2) {
throw new Error('IE < 9 cannot support extra params to setTimeout without a polyfill');
}
return timer.setTimeout(fn, delay);
}
return Function.prototype.apply.apply(timer.setTimeout, [global, arguments]);
};
self.setInterval = function(fn, delay, params) {
if (legacyIE()) {
if (arguments.length > 2) {
throw new Error('IE < 9 cannot support extra params to setInterval without a polyfill');
}
return timer.setInterval(fn, delay);
}
return Function.prototype.apply.apply(timer.setInterval, [global, arguments]);
};
self.clearTimeout = function(id) {
return Function.prototype.call.apply(timer.clearTimeout, [global, id]);
};
self.clearInterval = function(id) {
return Function.prototype.call.apply(timer.clearInterval, [global, id]);
};
self.tick = function(millis) {
if (installed) {
delayedFunctionScheduler.tick(millis, function(millis) { mockDate.tick(millis); });
} else {
throw new Error('Mock clock is not installed, use jasmine.clock().install()');
}
};
return self;
function originalTimingFunctionsIntact() {
return global.setTimeout === realTimingFunctions.setTimeout &&
global.clearTimeout === realTimingFunctions.clearTimeout &&
global.setInterval === realTimingFunctions.setInterval &&
global.clearInterval === realTimingFunctions.clearInterval;
}
function legacyIE() {
//if these methods are polyfilled, apply will be present
return !(realTimingFunctions.setTimeout || realTimingFunctions.setInterval).apply;
}
function replace(dest, source) {
for (var prop in source) {
dest[prop] = source[prop];
}
}
function setTimeout(fn, delay) {
return delayedFunctionScheduler.scheduleFunction(fn, delay, argSlice(arguments, 2));
}
function clearTimeout(id) {
return delayedFunctionScheduler.removeFunctionWithId(id);
}
function setInterval(fn, interval) {
return delayedFunctionScheduler.scheduleFunction(fn, interval, argSlice(arguments, 2), true);
}
function clearInterval(id) {
return delayedFunctionScheduler.removeFunctionWithId(id);
}
function argSlice(argsObj, n) {
return Array.prototype.slice.call(argsObj, n);
}
}
return Clock;
};
getJasmineRequireObj().DelayedFunctionScheduler = function() {
function DelayedFunctionScheduler() {
var self = this;
var scheduledLookup = [];
var scheduledFunctions = {};
var currentTime = 0;
var delayedFnCount = 0;
self.tick = function(millis, tickDate) {
millis = millis || 0;
var endTime = currentTime + millis;
runScheduledFunctions(endTime, tickDate);
currentTime = endTime;
};
self.scheduleFunction = function(funcToCall, millis, params, recurring, timeoutKey, runAtMillis) {
var f;
if (typeof(funcToCall) === 'string') {
/* jshint evil: true */
f = function() { return eval(funcToCall); };
/* jshint evil: false */
} else {
f = funcToCall;
}
millis = millis || 0;
timeoutKey = timeoutKey || ++delayedFnCount;
runAtMillis = runAtMillis || (currentTime + millis);
var funcToSchedule = {
runAtMillis: runAtMillis,
funcToCall: f,
recurring: recurring,
params: params,
timeoutKey: timeoutKey,
millis: millis
};
if (runAtMillis in scheduledFunctions) {
scheduledFunctions[runAtMillis].push(funcToSchedule);
} else {
scheduledFunctions[runAtMillis] = [funcToSchedule];
scheduledLookup.push(runAtMillis);
scheduledLookup.sort(function (a, b) {
return a - b;
});
}
return timeoutKey;
};
self.removeFunctionWithId = function(timeoutKey) {
for (var runAtMillis in scheduledFunctions) {
var funcs = scheduledFunctions[runAtMillis];
var i = indexOfFirstToPass(funcs, function (func) {
return func.timeoutKey === timeoutKey;
});
if (i > -1) {
if (funcs.length === 1) {
delete scheduledFunctions[runAtMillis];
deleteFromLookup(runAtMillis);
} else {
funcs.splice(i, 1);
}
// intervals get rescheduled when executed, so there's never more
// than a single scheduled function with a given timeoutKey
break;
}
}
};
return self;
function indexOfFirstToPass(array, testFn) {
var index = -1;
for (var i = 0; i < array.length; ++i) {
if (testFn(array[i])) {
index = i;
break;
}
}
return index;
}
function deleteFromLookup(key) {
var value = Number(key);
var i = indexOfFirstToPass(scheduledLookup, function (millis) {
return millis === value;
});
if (i > -1) {
scheduledLookup.splice(i, 1);
}
}
function reschedule(scheduledFn) {
self.scheduleFunction(scheduledFn.funcToCall,
scheduledFn.millis,
scheduledFn.params,
true,
scheduledFn.timeoutKey,
scheduledFn.runAtMillis + scheduledFn.millis);
}
function forEachFunction(funcsToRun, callback) {
for (var i = 0; i < funcsToRun.length; ++i) {
callback(funcsToRun[i]);
}
}
function runScheduledFunctions(endTime, tickDate) {
tickDate = tickDate || function() {};
if (scheduledLookup.length === 0 || scheduledLookup[0] > endTime) {
tickDate(endTime - currentTime);
return;
}
do {
var newCurrentTime = scheduledLookup.shift();
tickDate(newCurrentTime - currentTime);
currentTime = newCurrentTime;
var funcsToRun = scheduledFunctions[currentTime];
delete scheduledFunctions[currentTime];
forEachFunction(funcsToRun, function(funcToRun) {
if (funcToRun.recurring) {
reschedule(funcToRun);
}
});
forEachFunction(funcsToRun, function(funcToRun) {
funcToRun.funcToCall.apply(null, funcToRun.params || []);
});
} while (scheduledLookup.length > 0 &&
// checking first if we're out of time prevents setTimeout(0)
// scheduled in a funcToRun from forcing an extra iteration
currentTime !== endTime &&
scheduledLookup[0] <= endTime);
// ran out of functions to call, but still time left on the clock
if (currentTime !== endTime) {
tickDate(endTime - currentTime);
}
}
}
return DelayedFunctionScheduler;
};
getJasmineRequireObj().ExceptionFormatter = function() {
function ExceptionFormatter() {
this.message = function(error) {
var message = '';
if (error.name && error.message) {
message += error.name + ': ' + error.message;
} else {
message += error.toString() + ' thrown';
}
if (error.fileName || error.sourceURL) {
message += ' in ' + (error.fileName || error.sourceURL);
}
if (error.line || error.lineNumber) {
message += ' (line ' + (error.line || error.lineNumber) + ')';
}
return message;
};
this.stack = function(error) {
return error ? error.stack : null;
};
}
return ExceptionFormatter;
};
getJasmineRequireObj().Expectation = function() {
function Expectation(options) {
this.util = options.util || { buildFailureMessage: function() {} };
this.customEqualityTesters = options.customEqualityTesters || [];
this.actual = options.actual;
this.addExpectationResult = options.addExpectationResult || function(){};
this.isNot = options.isNot;
var customMatchers = options.customMatchers || {};
for (var matcherName in customMatchers) {
this[matcherName] = Expectation.prototype.wrapCompare(matcherName, customMatchers[matcherName]);
}
}
Expectation.prototype.wrapCompare = function(name, matcherFactory) {
return function() {
var args = Array.prototype.slice.call(arguments, 0),
expected = args.slice(0),
message = '';
args.unshift(this.actual);
var matcher = matcherFactory(this.util, this.customEqualityTesters),
matcherCompare = matcher.compare;
function defaultNegativeCompare() {
var result = matcher.compare.apply(null, args);
result.pass = !result.pass;
return result;
}
if (this.isNot) {
matcherCompare = matcher.negativeCompare || defaultNegativeCompare;
}
var result = matcherCompare.apply(null, args);
if (!result.pass) {
if (!result.message) {
args.unshift(this.isNot);
args.unshift(name);
message = this.util.buildFailureMessage.apply(null, args);
} else {
if (Object.prototype.toString.apply(result.message) === '[object Function]') {
message = result.message();
} else {
message = result.message;
}
}
}
if (expected.length == 1) {
expected = expected[0];
}
// TODO: how many of these params are needed?
this.addExpectationResult(
result.pass,
{
matcherName: name,
passed: result.pass,
message: message,
actual: this.actual,
expected: expected // TODO: this may need to be arrayified/sliced
}
);
};
};
Expectation.addCoreMatchers = function(matchers) {
var prototype = Expectation.prototype;
for (var matcherName in matchers) {
var matcher = matchers[matcherName];
prototype[matcherName] = prototype.wrapCompare(matcherName, matcher);
}
};
Expectation.Factory = function(options) {
options = options || {};
var expect = new Expectation(options);
// TODO: this would be nice as its own Object - NegativeExpectation
// TODO: copy instead of mutate options
options.isNot = true;
expect.not = new Expectation(options);
return expect;
};
return Expectation;
};
//TODO: expectation result may make more sense as a presentation of an expectation.
getJasmineRequireObj().buildExpectationResult = function() {
function buildExpectationResult(options) {
var messageFormatter = options.messageFormatter || function() {},
stackFormatter = options.stackFormatter || function() {};
var result = {
matcherName: options.matcherName,
message: message(),
stack: stack(),
passed: options.passed
};
if(!result.passed) {
result.expected = options.expected;
result.actual = options.actual;
}
return result;
function message() {
if (options.passed) {
return 'Passed.';
} else if (options.message) {
return options.message;
} else if (options.error) {
return messageFormatter(options.error);
}
return '';
}
function stack() {
if (options.passed) {
return '';
}
var error = options.error;
if (!error) {
try {
throw new Error(message());
} catch (e) {
error = e;
}
}
return stackFormatter(error);
}
}
return buildExpectationResult;
};
getJasmineRequireObj().MockDate = function() {
function MockDate(global) {
var self = this;
var currentTime = 0;
if (!global || !global.Date) {
self.install = function() {};
self.tick = function() {};
self.uninstall = function() {};
return self;
}
var GlobalDate = global.Date;
self.install = function(mockDate) {
if (mockDate instanceof GlobalDate) {
currentTime = mockDate.getTime();
} else {
currentTime = new GlobalDate().getTime();
}
global.Date = FakeDate;
};
self.tick = function(millis) {
millis = millis || 0;
currentTime = currentTime + millis;
};
self.uninstall = function() {
currentTime = 0;
global.Date = GlobalDate;
};
createDateProperties();
return self;
function FakeDate() {
switch(arguments.length) {
case 0:
return new GlobalDate(currentTime);
case 1:
return new GlobalDate(arguments[0]);
case 2:
return new GlobalDate(arguments[0], arguments[1]);
case 3:
return new GlobalDate(arguments[0], arguments[1], arguments[2]);
case 4:
return new GlobalDate(arguments[0], arguments[1], arguments[2], arguments[3]);
case 5:
return new GlobalDate(arguments[0], arguments[1], arguments[2], arguments[3],
arguments[4]);
case 6:
return new GlobalDate(arguments[0], arguments[1], arguments[2], arguments[3],
arguments[4], arguments[5]);
default:
return new GlobalDate(arguments[0], arguments[1], arguments[2], arguments[3],
arguments[4], arguments[5], arguments[6]);
}
}
function createDateProperties() {
FakeDate.prototype = GlobalDate.prototype;
FakeDate.now = function() {
if (GlobalDate.now) {
return currentTime;
} else {
throw new Error('Browser does not support Date.now()');
}
};
FakeDate.toSource = GlobalDate.toSource;
FakeDate.toString = GlobalDate.toString;
FakeDate.parse = GlobalDate.parse;
FakeDate.UTC = GlobalDate.UTC;
}
}
return MockDate;
};
getJasmineRequireObj().pp = function(j$) {
function PrettyPrinter() {
this.ppNestLevel_ = 0;
this.seen = [];
}
PrettyPrinter.prototype.format = function(value) {
this.ppNestLevel_++;
try {
if (j$.util.isUndefined(value)) {
this.emitScalar('undefined');
} else if (value === null) {
this.emitScalar('null');
} else if (value === 0 && 1/value === -Infinity) {
this.emitScalar('-0');
} else if (value === j$.getGlobal()) {
this.emitScalar('<global>');
} else if (value.jasmineToString) {
this.emitScalar(value.jasmineToString());
} else if (typeof value === 'string') {
this.emitString(value);
} else if (j$.isSpy(value)) {
this.emitScalar('spy on ' + value.and.identity());
} else if (value instanceof RegExp) {
this.emitScalar(value.toString());
} else if (typeof value === 'function') {
this.emitScalar('Function');
} else if (typeof value.nodeType === 'number') {
this.emitScalar('HTMLNode');
} else if (value instanceof Date) {
this.emitScalar('Date(' + value + ')');
} else if (value.toString && typeof value === 'object' && !(value instanceof Array) && value.toString !== Object.prototype.toString) {
this.emitScalar(value.toString());
} else if (j$.util.arrayContains(this.seen, value)) {
this.emitScalar('<circular reference: ' + (j$.isArray_(value) ? 'Array' : 'Object') + '>');
} else if (j$.isArray_(value) || j$.isA_('Object', value)) {
this.seen.push(value);
if (j$.isArray_(value)) {
this.emitArray(value);
} else {
this.emitObject(value);
}
this.seen.pop();
} else {
this.emitScalar(value.toString());
}
} finally {
this.ppNestLevel_--;
}
};
PrettyPrinter.prototype.iterateObject = function(obj, fn) {
for (var property in obj) {
if (!Object.prototype.hasOwnProperty.call(obj, property)) { continue; }
fn(property, obj.__lookupGetter__ ? (!j$.util.isUndefined(obj.__lookupGetter__(property)) &&
obj.__lookupGetter__(property) !== null) : false);
}
};
PrettyPrinter.prototype.emitArray = j$.unimplementedMethod_;
PrettyPrinter.prototype.emitObject = j$.unimplementedMethod_;
PrettyPrinter.prototype.emitScalar = j$.unimplementedMethod_;
PrettyPrinter.prototype.emitString = j$.unimplementedMethod_;
function StringPrettyPrinter() {
PrettyPrinter.call(this);
this.string = '';
}
j$.util.inherit(StringPrettyPrinter, PrettyPrinter);
StringPrettyPrinter.prototype.emitScalar = function(value) {
this.append(value);
};
StringPrettyPrinter.prototype.emitString = function(value) {
this.append('\'' + value + '\'');
};
StringPrettyPrinter.prototype.emitArray = function(array) {
if (this.ppNestLevel_ > j$.MAX_PRETTY_PRINT_DEPTH) {
this.append('Array');
return;
}
var length = Math.min(array.length, j$.MAX_PRETTY_PRINT_ARRAY_LENGTH);
this.append('[ ');
for (var i = 0; i < length; i++) {
if (i > 0) {
this.append(', ');
}
this.format(array[i]);
}
if(array.length > length){
this.append(', ...');
}
var self = this;
var first = array.length === 0;
this.iterateObject(array, function(property, isGetter) {
if (property.match(/^\d+$/)) {
return;
}
if (first) {
first = false;
} else {
self.append(', ');
}
self.formatProperty(array, property, isGetter);
});
this.append(' ]');
};
StringPrettyPrinter.prototype.emitObject = function(obj) {
var constructorName = obj.constructor ? j$.fnNameFor(obj.constructor) : 'null';
this.append(constructorName);
if (this.ppNestLevel_ > j$.MAX_PRETTY_PRINT_DEPTH) {
return;
}
var self = this;
this.append('({ ');
var first = true;
this.iterateObject(obj, function(property, isGetter) {
if (first) {
first = false;
} else {
self.append(', ');
}
self.formatProperty(obj, property, isGetter);
});
this.append(' })');
};
StringPrettyPrinter.prototype.formatProperty = function(obj, property, isGetter) {
this.append(property);
this.append(': ');
if (isGetter) {
this.append('<getter>');
} else {
this.format(obj[property]);
}
};
StringPrettyPrinter.prototype.append = function(value) {
this.string += value;
};
return function(value) {
var stringPrettyPrinter = new StringPrettyPrinter();
stringPrettyPrinter.format(value);
return stringPrettyPrinter.string;
};
};
getJasmineRequireObj().QueueRunner = function(j$) {
function once(fn) {
var called = false;
return function() {
if (!called) {
called = true;
fn();
}
return null;
};
}
function QueueRunner(attrs) {
this.queueableFns = attrs.queueableFns || [];
this.onComplete = attrs.onComplete || function() {};
this.clearStack = attrs.clearStack || function(fn) {fn();};
this.onException = attrs.onException || function() {};
this.catchException = attrs.catchException || function() { return true; };
this.userContext = attrs.userContext || {};
this.timeout = attrs.timeout || {setTimeout: setTimeout, clearTimeout: clearTimeout};
this.fail = attrs.fail || function() {};
}
QueueRunner.prototype.execute = function() {
this.run(this.queueableFns, 0);
};
QueueRunner.prototype.run = function(queueableFns, recursiveIndex) {
var length = queueableFns.length,
self = this,
iterativeIndex;
for(iterativeIndex = recursiveIndex; iterativeIndex < length; iterativeIndex++) {
var queueableFn = queueableFns[iterativeIndex];
if (queueableFn.fn.length > 0) {
attemptAsync(queueableFn);
return;
} else {
attemptSync(queueableFn);
}
}
var runnerDone = iterativeIndex >= length;
if (runnerDone) {
this.clearStack(this.onComplete);
}
function attemptSync(queueableFn) {
try {
queueableFn.fn.call(self.userContext);
} catch (e) {
handleException(e, queueableFn);
}
}
function attemptAsync(queueableFn) {
var clearTimeout = function () {
Function.prototype.apply.apply(self.timeout.clearTimeout, [j$.getGlobal(), [timeoutId]]);
},
next = once(function () {
clearTimeout(timeoutId);
self.run(queueableFns, iterativeIndex + 1);
}),
timeoutId;
next.fail = function() {
self.fail.apply(null, arguments);
next();
};
if (queueableFn.timeout) {
timeoutId = Function.prototype.apply.apply(self.timeout.setTimeout, [j$.getGlobal(), [function() {
var error = new Error('Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.');
onException(error);
next();
}, queueableFn.timeout()]]);
}
try {
queueableFn.fn.call(self.userContext, next);
} catch (e) {
handleException(e, queueableFn);
next();
}
}
function onException(e) {
self.onException(e);
}
function handleException(e, queueableFn) {
onException(e);
if (!self.catchException(e)) {
//TODO: set a var when we catch an exception and
//use a finally block to close the loop in a nice way..
throw e;
}
}
};
return QueueRunner;
};
getJasmineRequireObj().ReportDispatcher = function() {
function ReportDispatcher(methods) {
var dispatchedMethods = methods || [];
for (var i = 0; i < dispatchedMethods.length; i++) {
var method = dispatchedMethods[i];
this[method] = (function(m) {
return function() {
dispatch(m, arguments);
};
}(method));
}
var reporters = [];
var fallbackReporter = null;
this.addReporter = function(reporter) {
reporters.push(reporter);
};
this.provideFallbackReporter = function(reporter) {
fallbackReporter = reporter;
};
this.clearReporters = function() {
reporters = [];
};
return this;
function dispatch(method, args) {
if (reporters.length === 0 && fallbackReporter !== null) {
reporters.push(fallbackReporter);
}
for (var i = 0; i < reporters.length; i++) {
var reporter = reporters[i];
if (reporter[method]) {
reporter[method].apply(reporter, args);
}
}
}
}
return ReportDispatcher;
};
getJasmineRequireObj().SpyRegistry = function(j$) {
var getErrorMsg = j$.formatErrorMsg('<spyOn>', 'spyOn(<object>, <methodName>)');
function SpyRegistry(options) {
options = options || {};
var currentSpies = options.currentSpies || function() { return []; };
this.allowRespy = function(allow){
this.respy = allow;
};
this.spyOn = function(obj, methodName) {
if (j$.util.isUndefined(obj)) {
throw new Error(getErrorMsg('could not find an object to spy upon for ' + methodName + '()'));
}
if (j$.util.isUndefined(methodName)) {
throw new Error(getErrorMsg('No method name supplied'));
}
if (j$.util.isUndefined(obj[methodName])) {
throw new Error(getErrorMsg(methodName + '() method does not exist'));
}
if (obj[methodName] && j$.isSpy(obj[methodName]) ) {
if ( !!this.respy ){
return obj[methodName];
}else {
throw new Error(getErrorMsg(methodName + ' has already been spied upon'));
}
}
var descriptor;
try {
descriptor = Object.getOwnPropertyDescriptor(obj, methodName);
} catch(e) {
// IE 8 doesn't support `definePropery` on non-DOM nodes
}
if (descriptor && !(descriptor.writable || descriptor.set)) {
throw new Error(getErrorMsg(methodName + ' is not declared writable or has no setter'));
}
var originalMethod = obj[methodName],
spiedMethod = j$.createSpy(methodName, originalMethod),
restoreStrategy;
if (Object.prototype.hasOwnProperty.call(obj, methodName)) {
restoreStrategy = function() {
obj[methodName] = originalMethod;
};
} else {
restoreStrategy = function() {
if (!delete obj[methodName]) {
obj[methodName] = originalMethod;
}
};
}
currentSpies().push({
restoreObjectToOriginalState: restoreStrategy
});
obj[methodName] = spiedMethod;
return spiedMethod;
};
this.clearSpies = function() {
var spies = currentSpies();
for (var i = spies.length - 1; i >= 0; i--) {
var spyEntry = spies[i];
spyEntry.restoreObjectToOriginalState();
}
};
}
return SpyRegistry;
};
getJasmineRequireObj().SpyStrategy = function(j$) {
function SpyStrategy(options) {
options = options || {};
var identity = options.name || 'unknown',
originalFn = options.fn || function() {},
getSpy = options.getSpy || function() {},
plan = function() {};
this.identity = function() {
return identity;
};
this.exec = function() {
return plan.apply(this, arguments);
};
this.callThrough = function() {
plan = originalFn;
return getSpy();
};
this.returnValue = function(value) {
plan = function() {
return value;
};
return getSpy();
};
this.returnValues = function() {
var values = Array.prototype.slice.call(arguments);
plan = function () {
return values.shift();
};
return getSpy();
};
this.throwError = function(something) {
var error = (something instanceof Error) ? something : new Error(something);
plan = function() {
throw error;
};
return getSpy();
};
this.callFake = function(fn) {
if(!j$.isFunction_(fn)) {
throw new Error('Argument passed to callFake should be a function, got ' + fn);
}
plan = fn;
return getSpy();
};
this.stub = function(fn) {
plan = function() {};
return getSpy();
};
}
return SpyStrategy;
};
getJasmineRequireObj().Suite = function(j$) {
function Suite(attrs) {
this.env = attrs.env;
this.id = attrs.id;
this.parentSuite = attrs.parentSuite;
this.description = attrs.description;
this.expectationFactory = attrs.expectationFactory;
this.expectationResultFactory = attrs.expectationResultFactory;
this.throwOnExpectationFailure = !!attrs.throwOnExpectationFailure;
this.beforeFns = [];
this.afterFns = [];
this.beforeAllFns = [];
this.afterAllFns = [];
this.disabled = false;
this.children = [];
this.result = {
id: this.id,
description: this.description,
fullName: this.getFullName(),
failedExpectations: []
};
}
Suite.prototype.expect = function(actual) {
return this.expectationFactory(actual, this);
};
Suite.prototype.getFullName = function() {
var fullName = [];
for (var parentSuite = this; parentSuite; parentSuite = parentSuite.parentSuite) {
if (parentSuite.parentSuite) {
fullName.unshift(parentSuite.description);
}
}
return fullName.join(' ');
};
Suite.prototype.disable = function() {
this.disabled = true;
};
Suite.prototype.pend = function(message) {
this.markedPending = true;
};
Suite.prototype.beforeEach = function(fn) {
this.beforeFns.unshift(fn);
};
Suite.prototype.beforeAll = function(fn) {
this.beforeAllFns.push(fn);
};
Suite.prototype.afterEach = function(fn) {
this.afterFns.unshift(fn);
};
Suite.prototype.afterAll = function(fn) {
this.afterAllFns.push(fn);
};
Suite.prototype.addChild = function(child) {
this.children.push(child);
};
Suite.prototype.status = function() {
if (this.disabled) {
return 'disabled';
}
if (this.markedPending) {
return 'pending';
}
if (this.result.failedExpectations.length > 0) {
return 'failed';
} else {
return 'finished';
}
};
Suite.prototype.isExecutable = function() {
return !this.disabled;
};
Suite.prototype.canBeReentered = function() {
return this.beforeAllFns.length === 0 && this.afterAllFns.length === 0;
};
Suite.prototype.getResult = function() {
this.result.status = this.status();
return this.result;
};
Suite.prototype.sharedUserContext = function() {
if (!this.sharedContext) {
this.sharedContext = this.parentSuite ? clone(this.parentSuite.sharedUserContext()) : {};
}
return this.sharedContext;
};
Suite.prototype.clonedSharedUserContext = function() {
return clone(this.sharedUserContext());
};
Suite.prototype.onException = function() {
if (arguments[0] instanceof j$.errors.ExpectationFailed) {
return;
}
if(isAfterAll(this.children)) {
var data = {
matcherName: '',
passed: false,
expected: '',
actual: '',
error: arguments[0]
};
this.result.failedExpectations.push(this.expectationResultFactory(data));
} else {
for (var i = 0; i < this.children.length; i++) {
var child = this.children[i];
child.onException.apply(child, arguments);
}
}
};
Suite.prototype.addExpectationResult = function () {
if(isAfterAll(this.children) && isFailure(arguments)){
var data = arguments[1];
this.result.failedExpectations.push(this.expectationResultFactory(data));
if(this.throwOnExpectationFailure) {
throw new j$.errors.ExpectationFailed();
}
} else {
for (var i = 0; i < this.children.length; i++) {
var child = this.children[i];
try {
child.addExpectationResult.apply(child, arguments);
} catch(e) {
// keep going
}
}
}
};
function isAfterAll(children) {
return children && children[0].result.status;
}
function isFailure(args) {
return !args[0];
}
function clone(obj) {
var clonedObj = {};
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
clonedObj[prop] = obj[prop];
}
}
return clonedObj;
}
return Suite;
};
Iif (typeof window == void 0 && typeof exports == 'object') {
exports.Suite = jasmineRequire.Suite;
}
getJasmineRequireObj().Timer = function() {
var defaultNow = (function(Date) {
return function() { return new Date().getTime(); };
})(Date);
function Timer(options) {
options = options || {};
var now = options.now || defaultNow,
startTime;
this.start = function() {
startTime = now();
};
this.elapsed = function() {
return now() - startTime;
};
}
return Timer;
};
getJasmineRequireObj().TreeProcessor = function() {
function TreeProcessor(attrs) {
var tree = attrs.tree,
runnableIds = attrs.runnableIds,
queueRunnerFactory = attrs.queueRunnerFactory,
nodeStart = attrs.nodeStart || function() {},
nodeComplete = attrs.nodeComplete || function() {},
orderChildren = attrs.orderChildren || function(node) { return node.children; },
stats = { valid: true },
processed = false,
defaultMin = Infinity,
defaultMax = 1 - Infinity;
this.processTree = function() {
processNode(tree, false);
processed = true;
return stats;
};
this.execute = function(done) {
if (!processed) {
this.processTree();
}
if (!stats.valid) {
throw 'invalid order';
}
var childFns = wrapChildren(tree, 0);
queueRunnerFactory({
queueableFns: childFns,
userContext: tree.sharedUserContext(),
onException: function() {
tree.onException.apply(tree, arguments);
},
onComplete: done
});
};
function runnableIndex(id) {
for (var i = 0; i < runnableIds.length; i++) {
if (runnableIds[i] === id) {
return i;
}
}
}
function processNode(node, parentEnabled) {
var executableIndex = runnableIndex(node.id);
if (executableIndex !== undefined) {
parentEnabled = true;
}
parentEnabled = parentEnabled && node.isExecutable();
if (!node.children) {
stats[node.id] = {
executable: parentEnabled && node.isExecutable(),
segments: [{
index: 0,
owner: node,
nodes: [node],
min: startingMin(executableIndex),
max: startingMax(executableIndex)
}]
};
} else {
var hasExecutableChild = false;
var orderedChildren = orderChildren(node);
for (var i = 0; i < orderedChildren.length; i++) {
var child = orderedChildren[i];
processNode(child, parentEnabled);
if (!stats.valid) {
return;
}
var childStats = stats[child.id];
hasExecutableChild = hasExecutableChild || childStats.executable;
}
stats[node.id] = {
executable: hasExecutableChild
};
segmentChildren(node, orderedChildren, stats[node.id], executableIndex);
if (!node.canBeReentered() && stats[node.id].segments.length > 1) {
stats = { valid: false };
}
}
}
function startingMin(executableIndex) {
return executableIndex === undefined ? defaultMin : executableIndex;
}
function startingMax(executableIndex) {
return executableIndex === undefined ? defaultMax : executableIndex;
}
function segmentChildren(node, orderedChildren, nodeStats, executableIndex) {
var currentSegment = { index: 0, owner: node, nodes: [], min: startingMin(executableIndex), max: startingMax(executableIndex) },
result = [currentSegment],
lastMax = defaultMax,
orderedChildSegments = orderChildSegments(orderedChildren);
function isSegmentBoundary(minIndex) {
return lastMax !== defaultMax && minIndex !== defaultMin && lastMax < minIndex - 1;
}
for (var i = 0; i < orderedChildSegments.length; i++) {
var childSegment = orderedChildSegments[i],
maxIndex = childSegment.max,
minIndex = childSegment.min;
if (isSegmentBoundary(minIndex)) {
currentSegment = {index: result.length, owner: node, nodes: [], min: defaultMin, max: defaultMax};
result.push(currentSegment);
}
currentSegment.nodes.push(childSegment);
currentSegment.min = Math.min(currentSegment.min, minIndex);
currentSegment.max = Math.max(currentSegment.max, maxIndex);
lastMax = maxIndex;
}
nodeStats.segments = result;
}
function orderChildSegments(children) {
var specifiedOrder = [],
unspecifiedOrder = [];
for (var i = 0; i < children.length; i++) {
var child = children[i],
segments = stats[child.id].segments;
for (var j = 0; j < segments.length; j++) {
var seg = segments[j];
if (seg.min === defaultMin) {
unspecifiedOrder.push(seg);
} else {
specifiedOrder.push(seg);
}
}
}
specifiedOrder.sort(function(a, b) {
return a.min - b.min;
});
return specifiedOrder.concat(unspecifiedOrder);
}
function executeNode(node, segmentNumber) {
if (node.children) {
return {
fn: function(done) {
nodeStart(node);
queueRunnerFactory({
onComplete: function() {
nodeComplete(node, node.getResult());
done();
},
queueableFns: wrapChildren(node, segmentNumber),
userContext: node.sharedUserContext(),
onException: function() {
node.onException.apply(node, arguments);
}
});
}
};
} else {
return {
fn: function(done) { node.execute(done, stats[node.id].executable); }
};
}
}
function wrapChildren(node, segmentNumber) {
var result = [],
segmentChildren = stats[node.id].segments[segmentNumber].nodes;
for (var i = 0; i < segmentChildren.length; i++) {
result.push(executeNode(segmentChildren[i].owner, segmentChildren[i].index));
}
if (!stats[node.id].executable) {
return result;
}
return node.beforeAllFns.concat(result).concat(node.afterAllFns);
}
}
return TreeProcessor;
};
getJasmineRequireObj().Any = function(j$) {
function Any(expectedObject) {
if (typeof expectedObject === 'undefined') {
throw new TypeError(
'jasmine.any() expects to be passed a constructor function. ' +
'Please pass one or use jasmine.anything() to match any object.'
);
}
this.expectedObject = expectedObject;
}
Any.prototype.asymmetricMatch = function(other) {
if (this.expectedObject == String) {
return typeof other == 'string' || other instanceof String;
}
if (this.expectedObject == Number) {
return typeof other == 'number' || other instanceof Number;
}
if (this.expectedObject == Function) {
return typeof other == 'function' || other instanceof Function;
}
if (this.expectedObject == Object) {
return typeof other == 'object';
}
if (this.expectedObject == Boolean) {
return typeof other == 'boolean';
}
return other instanceof this.expectedObject;
};
Any.prototype.jasmineToString = function() {
return '<jasmine.any(' + j$.fnNameFor(this.expectedObject) + ')>';
};
return Any;
};
getJasmineRequireObj().Anything = function(j$) {
function Anything() {}
Anything.prototype.asymmetricMatch = function(other) {
return !j$.util.isUndefined(other) && other !== null;
};
Anything.prototype.jasmineToString = function() {
return '<jasmine.anything>';
};
return Anything;
};
getJasmineRequireObj().ArrayContaining = function(j$) {
function ArrayContaining(sample) {
this.sample = sample;
}
ArrayContaining.prototype.asymmetricMatch = function(other) {
var className = Object.prototype.toString.call(this.sample);
if (className !== '[object Array]') { throw new Error('You must provide an array to arrayContaining, not \'' + this.sample + '\'.'); }
for (var i = 0; i < this.sample.length; i++) {
var item = this.sample[i];
if (!j$.matchersUtil.contains(other, item)) {
return false;
}
}
return true;
};
ArrayContaining.prototype.jasmineToString = function () {
return '<jasmine.arrayContaining(' + jasmine.pp(this.sample) +')>';
};
return ArrayContaining;
};
getJasmineRequireObj().ObjectContaining = function(j$) {
function ObjectContaining(sample) {
this.sample = sample;
}
function getPrototype(obj) {
if (Object.getPrototypeOf) {
return Object.getPrototypeOf(obj);
}
if (obj.constructor.prototype == obj) {
return null;
}
return obj.constructor.prototype;
}
function hasProperty(obj, property) {
if (!obj) {
return false;
}
if (Object.prototype.hasOwnProperty.call(obj, property)) {
return true;
}
return hasProperty(getPrototype(obj), property);
}
ObjectContaining.prototype.asymmetricMatch = function(other) {
if (typeof(this.sample) !== 'object') { throw new Error('You must provide an object to objectContaining, not \''+this.sample+'\'.'); }
for (var property in this.sample) {
if (!hasProperty(other, property) ||
!j$.matchersUtil.equals(this.sample[property], other[property])) {
return false;
}
}
return true;
};
ObjectContaining.prototype.jasmineToString = function() {
return '<jasmine.objectContaining(' + j$.pp(this.sample) + ')>';
};
return ObjectContaining;
};
getJasmineRequireObj().StringMatching = function(j$) {
function StringMatching(expected) {
if (!j$.isString_(expected) && !j$.isA_('RegExp', expected)) {
throw new Error('Expected is not a String or a RegExp');
}
this.regexp = new RegExp(expected);
}
StringMatching.prototype.asymmetricMatch = function(other) {
return this.regexp.test(other);
};
StringMatching.prototype.jasmineToString = function() {
return '<jasmine.stringMatching(' + this.regexp + ')>';
};
return StringMatching;
};
getJasmineRequireObj().errors = function() {
function ExpectationFailed() {}
ExpectationFailed.prototype = new Error();
ExpectationFailed.prototype.constructor = ExpectationFailed;
return {
ExpectationFailed: ExpectationFailed
};
};
getJasmineRequireObj().formatErrorMsg = function() {
function generateErrorMsg(domain, usage) {
var usageDefinition = usage ? '\nUsage: ' + usage : '';
return function errorMsg(msg) {
return domain + ' : ' + msg + usageDefinition;
};
}
return generateErrorMsg;
};
getJasmineRequireObj().matchersUtil = function(j$) {
// TODO: what to do about jasmine.pp not being inject? move to JSON.stringify? gut PrettyPrinter?
return {
equals: function(a, b, customTesters) {
customTesters = customTesters || [];
return eq(a, b, [], [], customTesters);
},
contains: function(haystack, needle, customTesters) {
customTesters = customTesters || [];
if ((Object.prototype.toString.apply(haystack) === '[object Array]') ||
(!!haystack && !haystack.indexOf))
{
for (var i = 0; i < haystack.length; i++) {
if (eq(haystack[i], needle, [], [], customTesters)) {
return true;
}
}
return false;
}
return !!haystack && haystack.indexOf(needle) >= 0;
},
buildFailureMessage: function() {
var args = Array.prototype.slice.call(arguments, 0),
matcherName = args[0],
isNot = args[1],
actual = args[2],
expected = args.slice(3),
englishyPredicate = matcherName.replace(/[A-Z]/g, function(s) { return ' ' + s.toLowerCase(); });
var message = 'Expected ' +
j$.pp(actual) +
(isNot ? ' not ' : ' ') +
englishyPredicate;
if (expected.length > 0) {
for (var i = 0; i < expected.length; i++) {
if (i > 0) {
message += ',';
}
message += ' ' + j$.pp(expected[i]);
}
}
return message + '.';
}
};
function isAsymmetric(obj) {
return obj && j$.isA_('Function', obj.asymmetricMatch);
}
function asymmetricMatch(a, b) {
var asymmetricA = isAsymmetric(a),
asymmetricB = isAsymmetric(b);
if (asymmetricA && asymmetricB) {
return undefined;
}
if (asymmetricA) {
return a.asymmetricMatch(b);
}
if (asymmetricB) {
return b.asymmetricMatch(a);
}
}
// Equality function lovingly adapted from isEqual in
// [Underscore](http://underscorejs.org)
function eq(a, b, aStack, bStack, customTesters) {
var result = true;
var asymmetricResult = asymmetricMatch(a, b);
if (!j$.util.isUndefined(asymmetricResult)) {
return asymmetricResult;
}
for (var i = 0; i < customTesters.length; i++) {
var customTesterResult = customTesters[i](a, b);
if (!j$.util.isUndefined(customTesterResult)) {
return customTesterResult;
}
}
if (a instanceof Error && b instanceof Error) {
return a.message == b.message;
}
// Identical objects are equal. `0 === -0`, but they aren't identical.
// See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
if (a === b) { return a !== 0 || 1 / a == 1 / b; }
// A strict comparison is necessary because `null == undefined`.
if (a === null || b === null) { return a === b; }
var className = Object.prototype.toString.call(a);
if (className != Object.prototype.toString.call(b)) { return false; }
switch (className) {
// Strings, numbers, dates, and booleans are compared by value.
case '[object String]':
// Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
// equivalent to `new String("5")`.
return a == String(b);
case '[object Number]':
// `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
// other numeric values.
return a != +a ? b != +b : (a === 0 ? 1 / a == 1 / b : a == +b);
case '[object Date]':
case '[object Boolean]':
// Coerce dates and booleans to numeric primitive values. Dates are compared by their
// millisecond representations. Note that invalid dates with millisecond representations
// of `NaN` are not equivalent.
return +a == +b;
// RegExps are compared by their source patterns and flags.
case '[object RegExp]':
return a.source == b.source &&
a.global == b.global &&
a.multiline == b.multiline &&
a.ignoreCase == b.ignoreCase;
}
if (typeof a != 'object' || typeof b != 'object') { return false; }
var aIsDomNode = j$.isDomNode(a);
var bIsDomNode = j$.isDomNode(b);
if (aIsDomNode && bIsDomNode) {
// At first try to use DOM3 method isEqualNode
if (a.isEqualNode) {
return a.isEqualNode(b);
}
// IE8 doesn't support isEqualNode, try to use outerHTML && innerText
var aIsElement = a instanceof Element;
var bIsElement = b instanceof Element;
if (aIsElement && bIsElement) {
return a.outerHTML == b.outerHTML;
}
if (aIsElement || bIsElement) {
return false;
}
return a.innerText == b.innerText && a.textContent == b.textContent;
}
if (aIsDomNode || bIsDomNode) {
return false;
}
// Assume equality for cyclic structures. The algorithm for detecting cyclic
// structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
var length = aStack.length;
while (length--) {
// Linear search. Performance is inversely proportional to the number of
// unique nested structures.
if (aStack[length] == a) { return bStack[length] == b; }
}
// Add the first object to the stack of traversed objects.
aStack.push(a);
bStack.push(b);
var size = 0;
// Recursively compare objects and arrays.
// Compare array lengths to determine if a deep comparison is necessary.
if (className == '[object Array]') {
size = a.length;
if (size !== b.length) {
return false;
}
while (size--) {
result = eq(a[size], b[size], aStack, bStack, customTesters);
if (!result) {
return false;
}
}
} else {
// Objects with different constructors are not equivalent, but `Object`s
// or `Array`s from different frames are.
var aCtor = a.constructor, bCtor = b.constructor;
if (aCtor !== bCtor && !(isObjectConstructor(aCtor) &&
isObjectConstructor(bCtor))) {
return false;
}
}
// Deep compare objects.
var aKeys = keys(a, className == '[object Array]'), key;
size = aKeys.length;
// Ensure that both objects contain the same number of properties before comparing deep equality.
if (keys(b, className == '[object Array]').length !== size) { return false; }
while (size--) {
key = aKeys[size];
// Deep compare each member
result = has(b, key) && eq(a[key], b[key], aStack, bStack, customTesters);
if (!result) {
return false;
}
}
// Remove the first object from the stack of traversed objects.
aStack.pop();
bStack.pop();
return result;
function keys(obj, isArray) {
var allKeys = Object.keys ? Object.keys(obj) :
(function(o) {
var keys = [];
for (var key in o) {
if (has(o, key)) {
keys.push(key);
}
}
return keys;
})(obj);
if (!isArray) {
return allKeys;
}
var extraKeys = [];
if (allKeys.length === 0) {
return allKeys;
}
for (var x = 0; x < allKeys.length; x++) {
if (!allKeys[x].match(/^[0-9]+$/)) {
extraKeys.push(allKeys[x]);
}
}
return extraKeys;
}
}
function has(obj, key) {
return Object.prototype.hasOwnProperty.call(obj, key);
}
function isFunction(obj) {
return typeof obj === 'function';
}
function isObjectConstructor(ctor) {
// aCtor instanceof aCtor is true for the Object and Function
// constructors (since a constructor is-a Function and a function is-a
// Object). We don't just compare ctor === Object because the constructor
// might come from a different frame with different globals.
return isFunction(ctor) && ctor instanceof ctor;
}
};
getJasmineRequireObj().toBe = function() {
function toBe() {
return {
compare: function(actual, expected) {
return {
pass: actual === expected
};
}
};
}
return toBe;
};
getJasmineRequireObj().toBeCloseTo = function() {
function toBeCloseTo() {
return {
compare: function(actual, expected, precision) {
if (precision !== 0) {
precision = precision || 2;
}
return {
pass: Math.abs(expected - actual) < (Math.pow(10, -precision) / 2)
};
}
};
}
return toBeCloseTo;
};
getJasmineRequireObj().toBeDefined = function() {
function toBeDefined() {
return {
compare: function(actual) {
return {
pass: (void 0 !== actual)
};
}
};
}
return toBeDefined;
};
getJasmineRequireObj().toBeFalsy = function() {
function toBeFalsy() {
return {
compare: function(actual) {
return {
pass: !!!actual
};
}
};
}
return toBeFalsy;
};
getJasmineRequireObj().toBeGreaterThan = function() {
function toBeGreaterThan() {
return {
compare: function(actual, expected) {
return {
pass: actual > expected
};
}
};
}
return toBeGreaterThan;
};
getJasmineRequireObj().toBeGreaterThanOrEqual = function() {
function toBeGreaterThanOrEqual() {
return {
compare: function(actual, expected) {
return {
pass: actual >= expected
};
}
};
}
return toBeGreaterThanOrEqual;
};
getJasmineRequireObj().toBeLessThan = function() {
function toBeLessThan() {
return {
compare: function(actual, expected) {
return {
pass: actual < expected
};
}
};
}
return toBeLessThan;
};
getJasmineRequireObj().toBeLessThanOrEqual = function() {
function toBeLessThanOrEqual() {
return {
compare: function(actual, expected) {
return {
pass: actual <= expected
};
}
};
}
return toBeLessThanOrEqual;
};
getJasmineRequireObj().toBeNaN = function(j$) {
function toBeNaN() {
return {
compare: function(actual) {
var result = {
pass: (actual !== actual)
};
if (result.pass) {
result.message = 'Expected actual not to be NaN.';
} else {
result.message = function() { return 'Expected ' + j$.pp(actual) + ' to be NaN.'; };
}
return result;
}
};
}
return toBeNaN;
};
getJasmineRequireObj().toBeNull = function() {
function toBeNull() {
return {
compare: function(actual) {
return {
pass: actual === null
};
}
};
}
return toBeNull;
};
getJasmineRequireObj().toBeTruthy = function() {
function toBeTruthy() {
return {
compare: function(actual) {
return {
pass: !!actual
};
}
};
}
return toBeTruthy;
};
getJasmineRequireObj().toBeUndefined = function() {
function toBeUndefined() {
return {
compare: function(actual) {
return {
pass: void 0 === actual
};
}
};
}
return toBeUndefined;
};
getJasmineRequireObj().toContain = function() {
function toContain(util, customEqualityTesters) {
customEqualityTesters = customEqualityTesters || [];
return {
compare: function(actual, expected) {
return {
pass: util.contains(actual, expected, customEqualityTesters)
};
}
};
}
return toContain;
};
getJasmineRequireObj().toEqual = function() {
function toEqual(util, customEqualityTesters) {
customEqualityTesters = customEqualityTesters || [];
return {
compare: function(actual, expected) {
var result = {
pass: false
};
result.pass = util.equals(actual, expected, customEqualityTesters);
return result;
}
};
}
return toEqual;
};
getJasmineRequireObj().toHaveBeenCalled = function(j$) {
var getErrorMsg = j$.formatErrorMsg('<toHaveBeenCalled>', 'expect(<spyObj>).toHaveBeenCalled()');
function toHaveBeenCalled() {
return {
compare: function(actual) {
var result = {};
if (!j$.isSpy(actual)) {
throw new Error(getErrorMsg('Expected a spy, but got ' + j$.pp(actual) + '.'));
}
if (arguments.length > 1) {
throw new Error(getErrorMsg('Does not take arguments, use toHaveBeenCalledWith'));
}
result.pass = actual.calls.any();
result.message = result.pass ?
'Expected spy ' + actual.and.identity() + ' not to have been called.' :
'Expected spy ' + actual.and.identity() + ' to have been called.';
return result;
}
};
}
return toHaveBeenCalled;
};
getJasmineRequireObj().toHaveBeenCalledTimes = function(j$) {
var getErrorMsg = j$.formatErrorMsg('<toHaveBeenCalledTimes>', 'expect(<spyObj>).toHaveBeenCalledTimes(<Number>)');
function toHaveBeenCalledTimes() {
return {
compare: function(actual, expected) {
if (!j$.isSpy(actual)) {
throw new Error(getErrorMsg('Expected a spy, but got ' + j$.pp(actual) + '.'));
}
var args = Array.prototype.slice.call(arguments, 0),
result = { pass: false };
if (!j$.isNumber_(expected)){
throw new Error(getErrorMsg('The expected times failed is a required argument and must be a number.'));
}
actual = args[0];
var calls = actual.calls.count();
var timesMessage = expected === 1 ? 'once' : expected + ' times';
result.pass = calls === expected;
result.message = result.pass ?
'Expected spy ' + actual.and.identity() + ' not to have been called ' + timesMessage + '. It was called ' + calls + ' times.' :
'Expected spy ' + actual.and.identity() + ' to have been called ' + timesMessage + '. It was called ' + calls + ' times.';
return result;
}
};
}
return toHaveBeenCalledTimes;
};
getJasmineRequireObj().toHaveBeenCalledWith = function(j$) {
var getErrorMsg = j$.formatErrorMsg('<toHaveBeenCalledWith>', 'expect(<spyObj>).toHaveBeenCalledWith(...arguments)');
function toHaveBeenCalledWith(util, customEqualityTesters) {
return {
compare: function() {
var args = Array.prototype.slice.call(arguments, 0),
actual = args[0],
expectedArgs = args.slice(1),
result = { pass: false };
if (!j$.isSpy(actual)) {
throw new Error(getErrorMsg('Expected a spy, but got ' + j$.pp(actual) + '.'));
}
if (!actual.calls.any()) {
result.message = function() { return 'Expected spy ' + actual.and.identity() + ' to have been called with ' + j$.pp(expectedArgs) + ' but it was never called.'; };
return result;
}
if (util.contains(actual.calls.allArgs(), expectedArgs, customEqualityTesters)) {
result.pass = true;
result.message = function() { return 'Expected spy ' + actual.and.identity() + ' not to have been called with ' + j$.pp(expectedArgs) + ' but it was.'; };
} else {
result.message = function() { return 'Expected spy ' + actual.and.identity() + ' to have been called with ' + j$.pp(expectedArgs) + ' but actual calls were ' + j$.pp(actual.calls.allArgs()).replace(/^\[ | \]$/g, '') + '.'; };
}
return result;
}
};
}
return toHaveBeenCalledWith;
};
getJasmineRequireObj().toMatch = function(j$) {
var getErrorMsg = j$.formatErrorMsg('<toMatch>', 'expect(<expectation>).toMatch(<string> || <regexp>)');
function toMatch() {
return {
compare: function(actual, expected) {
if (!j$.isString_(expected) && !j$.isA_('RegExp', expected)) {
throw new Error(getErrorMsg('Expected is not a String or a RegExp'));
}
var regexp = new RegExp(expected);
return {
pass: regexp.test(actual)
};
}
};
}
return toMatch;
};
getJasmineRequireObj().toThrow = function(j$) {
var getErrorMsg = j$.formatErrorMsg('<toThrow>', 'expect(function() {<expectation>}).toThrow()');
function toThrow(util) {
return {
compare: function(actual, expected) {
var result = { pass: false },
threw = false,
thrown;
if (typeof actual != 'function') {
throw new Error(getErrorMsg('Actual is not a Function'));
}
try {
actual();
} catch (e) {
threw = true;
thrown = e;
}
if (!threw) {
result.message = 'Expected function to throw an exception.';
return result;
}
if (arguments.length == 1) {
result.pass = true;
result.message = function() { return 'Expected function not to throw, but it threw ' + j$.pp(thrown) + '.'; };
return result;
}
if (util.equals(thrown, expected)) {
result.pass = true;
result.message = function() { return 'Expected function not to throw ' + j$.pp(expected) + '.'; };
} else {
result.message = function() { return 'Expected function to throw ' + j$.pp(expected) + ', but it threw ' + j$.pp(thrown) + '.'; };
}
return result;
}
};
}
return toThrow;
};
getJasmineRequireObj().toThrowError = function(j$) {
var getErrorMsg = j$.formatErrorMsg('<toThrowError>', 'expect(function() {<expectation>}).toThrowError(<ErrorConstructor>, <message>)');
function toThrowError () {
return {
compare: function(actual) {
var threw = false,
pass = {pass: true},
fail = {pass: false},
thrown;
if (typeof actual != 'function') {
throw new Error(getErrorMsg('Actual is not a Function'));
}
var errorMatcher = getMatcher.apply(null, arguments);
try {
actual();
} catch (e) {
threw = true;
thrown = e;
}
if (!threw) {
fail.message = 'Expected function to throw an Error.';
return fail;
}
if (!(thrown instanceof Error)) {
fail.message = function() { return 'Expected function to throw an Error, but it threw ' + j$.pp(thrown) + '.'; };
return fail;
}
if (errorMatcher.hasNoSpecifics()) {
pass.message = 'Expected function not to throw an Error, but it threw ' + j$.fnNameFor(thrown) + '.';
return pass;
}
if (errorMatcher.matches(thrown)) {
pass.message = function() {
return 'Expected function not to throw ' + errorMatcher.errorTypeDescription + errorMatcher.messageDescription() + '.';
};
return pass;
} else {
fail.message = function() {
return 'Expected function to throw ' + errorMatcher.errorTypeDescription + errorMatcher.messageDescription() +
', but it threw ' + errorMatcher.thrownDescription(thrown) + '.';
};
return fail;
}
}
};
function getMatcher() {
var expected = null,
errorType = null;
if (arguments.length == 2) {
expected = arguments[1];
if (isAnErrorType(expected)) {
errorType = expected;
expected = null;
}
} else if (arguments.length > 2) {
errorType = arguments[1];
expected = arguments[2];
if (!isAnErrorType(errorType)) {
throw new Error(getErrorMsg('Expected error type is not an Error.'));
}
}
if (expected && !isStringOrRegExp(expected)) {
if (errorType) {
throw new Error(getErrorMsg('Expected error message is not a string or RegExp.'));
} else {
throw new Error(getErrorMsg('Expected is not an Error, string, or RegExp.'));
}
}
function messageMatch(message) {
if (typeof expected == 'string') {
return expected == message;
} else {
return expected.test(message);
}
}
return {
errorTypeDescription: errorType ? j$.fnNameFor(errorType) : 'an exception',
thrownDescription: function(thrown) {
var thrownName = errorType ? j$.fnNameFor(thrown.constructor) : 'an exception',
thrownMessage = '';
if (expected) {
thrownMessage = ' with message ' + j$.pp(thrown.message);
}
return thrownName + thrownMessage;
},
messageDescription: function() {
if (expected === null) {
return '';
} else if (expected instanceof RegExp) {
return ' with a message matching ' + j$.pp(expected);
} else {
return ' with message ' + j$.pp(expected);
}
},
hasNoSpecifics: function() {
return expected === null && errorType === null;
},
matches: function(error) {
return (errorType === null || error instanceof errorType) &&
(expected === null || messageMatch(error.message));
}
};
}
function isStringOrRegExp(potential) {
return potential instanceof RegExp || (typeof potential == 'string');
}
function isAnErrorType(type) {
if (typeof type !== 'function') {
return false;
}
var Surrogate = function() {};
Surrogate.prototype = type.prototype;
return (new Surrogate()) instanceof Error;
}
}
return toThrowError;
};
getJasmineRequireObj().interface = function(jasmine, env) {
var jasmineInterface = {
describe: function(description, specDefinitions) {
return env.describe(description, specDefinitions);
},
xdescribe: function(description, specDefinitions) {
return env.xdescribe(description, specDefinitions);
},
fdescribe: function(description, specDefinitions) {
return env.fdescribe(description, specDefinitions);
},
it: function() {
return env.it.apply(env, arguments);
},
xit: function() {
return env.xit.apply(env, arguments);
},
fit: function() {
return env.fit.apply(env, arguments);
},
beforeEach: function() {
return env.beforeEach.apply(env, arguments);
},
afterEach: function() {
return env.afterEach.apply(env, arguments);
},
beforeAll: function() {
return env.beforeAll.apply(env, arguments);
},
afterAll: function() {
return env.afterAll.apply(env, arguments);
},
expect: function(actual) {
return env.expect(actual);
},
pending: function() {
return env.pending.apply(env, arguments);
},
fail: function() {
return env.fail.apply(env, arguments);
},
spyOn: function(obj, methodName) {
return env.spyOn(obj, methodName);
},
jsApiReporter: new jasmine.JsApiReporter({
timer: new jasmine.Timer()
}),
jasmine: jasmine
};
jasmine.addCustomEqualityTester = function(tester) {
env.addCustomEqualityTester(tester);
};
jasmine.addMatchers = function(matchers) {
return env.addMatchers(matchers);
};
jasmine.clock = function() {
return env.clock;
};
return jasmineInterface;
};
getJasmineRequireObj().version = function() {
return '2.5.2';
};
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| adopter.js | 2.13% | (1 / 47) | 100% | (0 / 0) | 0% | (0 / 24) | 2.13% | (1 / 47) | |
| arrange.js | 0.89% | (1 / 112) | 0% | (0 / 2) | 0% | (0 / 36) | 0.89% | (1 / 112) | |
| array.js | 0.45% | (1 / 221) | 100% | (0 / 0) | 0% | (0 / 67) | 0.45% | (1 / 221) | |
| bare.js | 4.55% | (1 / 22) | 0% | (0 / 4) | 0% | (0 / 9) | 4.55% | (1 / 22) | |
| boxes.js | 0.88% | (1 / 114) | 100% | (0 / 0) | 0% | (0 / 35) | 0.88% | (1 / 114) | |
| circle.js | 0.92% | (1 / 109) | 100% | (0 / 0) | 0% | (0 / 46) | 0.92% | (1 / 109) | |
| clip.js | 3.03% | (1 / 33) | 100% | (0 / 0) | 0% | (0 / 14) | 3.03% | (1 / 33) | |
| color.js | 1.85% | (1 / 54) | 100% | (0 / 0) | 0% | (0 / 18) | 1.85% | (1 / 54) | |
| container.js | 0.43% | (1 / 231) | 0% | (0 / 6) | 0% | (0 / 87) | 0.43% | (1 / 231) | |
| defs.js | 16.67% | (1 / 6) | 100% | (0 / 0) | 0% | (0 / 3) | 16.67% | (1 / 6) | |
| easing.js | 10% | (1 / 10) | 100% | (0 / 0) | 0% | (0 / 6) | 10% | (1 / 10) | |
| element.js | 0.16% | (1 / 632) | 0% | (0 / 12) | 0% | (0 / 185) | 0.16% | (1 / 631) | |
| ellipse.js | 0.87% | (1 / 115) | 100% | (0 / 0) | 0% | (0 / 44) | 0.87% | (1 / 115) | |
| event.js | 0.32% | (1 / 311) | 0% | (0 / 6) | 0% | (0 / 100) | 0.33% | (1 / 304) | |
| fx.js | 0.06% | (1 / 1795) | 0% | (0 / 12) | 0% | (0 / 234) | 0.06% | (1 / 1793) | |
| gradient.js | 1.04% | (1 / 96) | 100% | (0 / 0) | 0% | (0 / 36) | 1.04% | (1 / 96) | |
| group.js | 1.32% | (1 / 76) | 100% | (0 / 0) | 0% | (0 / 29) | 1.32% | (1 / 76) | |
| helper.js | 10.26% | (4 / 39) | 12.5% | (1 / 8) | 0% | (0 / 5) | 10.53% | (4 / 38) | |
| hyperlink.js | 2.94% | (1 / 34) | 100% | (0 / 0) | 0% | (0 / 16) | 2.94% | (1 / 34) | |
| image.js | 0.71% | (1 / 141) | 100% | (0 / 0) | 0% | (0 / 58) | 0.72% | (1 / 139) | |
| line.js | 0.6% | (1 / 168) | 100% | (0 / 0) | 0% | (0 / 48) | 0.6% | (1 / 168) | |
| marker.js | 2.04% | (1 / 49) | 100% | (0 / 0) | 0% | (0 / 20) | 2.04% | (1 / 49) | |
| mask.js | 3.03% | (1 / 33) | 100% | (0 / 0) | 0% | (0 / 14) | 3.03% | (1 / 33) | |
| matrix.js | 0.33% | (1 / 304) | 100% | (0 / 0) | 0% | (0 / 78) | 0.33% | (1 / 304) | |
| memory.js | 2.44% | (1 / 41) | 100% | (0 / 0) | 0% | (0 / 12) | 2.44% | (1 / 41) | |
| nested.js | 16.67% | (1 / 6) | 100% | (0 / 0) | 0% | (0 / 4) | 16.67% | (1 / 6) | |
| number.js | 0.61% | (1 / 165) | 100% | (0 / 0) | 0% | (0 / 66) | 0.61% | (1 / 165) | |
| path.js | 0.62% | (1 / 161) | 100% | (0 / 0) | 0% | (0 / 61) | 0.62% | (1 / 161) | |
| pattern.js | 2.5% | (1 / 40) | 100% | (0 / 0) | 0% | (0 / 18) | 2.5% | (1 / 40) | |
| point.js | 1.41% | (1 / 71) | 100% | (0 / 0) | 0% | (0 / 30) | 1.41% | (1 / 71) | |
| polygon.js | 0.68% | (1 / 146) | 100% | (0 / 0) | 0% | (0 / 54) | 0.68% | (1 / 146) | |
| polyline.js | 0.68% | (1 / 146) | 100% | (0 / 0) | 0% | (0 / 54) | 0.68% | (1 / 146) | |
| rect.js | 0.93% | (1 / 108) | 100% | (0 / 0) | 0% | (0 / 43) | 0.93% | (1 / 108) | |
| regex.js | 2.04% | (1 / 49) | 100% | (0 / 0) | 0% | (0 / 27) | 2.04% | (1 / 49) | |
| selector.js | 3.57% | (1 / 28) | 100% | (0 / 0) | 0% | (0 / 11) | 3.57% | (1 / 28) | |
| set.js | 0.83% | (1 / 121) | 100% | (0 / 0) | 0% | (0 / 48) | 0.83% | (1 / 121) | |
| sugar.js | 0.48% | (1 / 208) | 100% | (0 / 0) | 0% | (0 / 68) | 0.48% | (1 / 208) | |
| svg.js | 1.56% | (1 / 64) | 0% | (0 / 2) | 0% | (0 / 24) | 1.56% | (1 / 64) | |
| symbol.js | 11.11% | (1 / 9) | 100% | (0 / 0) | 0% | (0 / 5) | 11.11% | (1 / 9) | |
| text.js | 0.52% | (1 / 191) | 100% | (0 / 0) | 0% | (0 / 67) | 0.52% | (1 / 191) | |
| textpath.js | 2.78% | (1 / 36) | 100% | (0 / 0) | 0% | (0 / 18) | 2.78% | (1 / 36) | |
| transformations.js | 0.57% | (1 / 176) | 100% | (0 / 0) | 0% | (0 / 51) | 0.57% | (1 / 176) | |
| tspan.js | 3.45% | (1 / 29) | 100% | (0 / 0) | 0% | (0 / 12) | 3.45% | (1 / 29) | |
| use.js | 4.76% | (1 / 21) | 100% | (0 / 0) | 0% | (0 / 10) | 4.76% | (1 / 21) | |
| utils.js | 16.67% | (1 / 6) | 100% | (0 / 0) | 0% | (0 / 4) | 16.67% | (1 / 6) | |
| viewbox.js | 1.09% | (1 / 92) | 100% | (0 / 0) | 0% | (0 / 26) | 1.09% | (1 / 92) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | 2 | describe('Adopter', function() {
var path, polyline, polygon, linearGradient, radialGradient
beforeEach(function() {
path = SVG.get('lineAB')
polyline = SVG.get('inlineSVG').select('polyline').first()
polygon = SVG.get('inlineSVG').select('polygon').first()
linearGradient = SVG.get('inlineSVG').select('linearGradient').first()
radialGradient = SVG.get('inlineSVG').select('radialGradient').first()
})
describe('with SVG.Doc instance', function() {
it('adopts the main svg document when parent() method is called on first level children', function() {
expect(path.parent() instanceof SVG.Doc).toBeTruthy()
})
it('defines a xmlns attribute', function() {
expect(path.parent().node.getAttribute('xmlns')).toBe(SVG.ns)
})
it('defines a version attribute', function() {
expect(path.parent().node.getAttribute('version')).toBe('1.1')
})
it('defines a xmlns:xlink attribute', function() {
expect(path.parent().node.getAttribute('xmlns:xlink')).toBe(SVG.xlink)
})
it('initializes a defs node', function() {
expect(path.parent()._defs).toBe(path.parent().defs())
})
})
describe('with SVG.Path instance', function() {
it('adopts an exiting path element', function() {
expect(path instanceof SVG.Path).toBeTruthy()
})
it('modifies an adopted element', function() {
path.fill('#f06')
expect(path.node.getAttribute('fill')).toBe('#ff0066')
})
it('parses d attribute to SVG.PathArray', function() {
expect(path.array() instanceof SVG.PathArray).toBeTruthy()
})
})
describe('with SVG.Polyline instance', function() {
it('parses points attribute to SVG.PointArray', function() {
expect(polyline.array() instanceof SVG.PointArray).toBeTruthy()
})
})
describe('with SVG.Polygon instance', function() {
it('parses points attribute to SVG.PointArray', function() {
expect(polygon.array() instanceof SVG.PointArray).toBeTruthy()
})
})
describe('with linear SVG.Gradient instance', function() {
it('is instance of SVG.Gradient', function() {
expect(linearGradient instanceof SVG.Gradient).toBeTruthy()
})
it('has type of linear', function() {
expect(linearGradient.type).toBe('linearGradient') // actually it should be 'linear'. see #606
})
})
describe('with radial SVG.Gradient instance', function() {
it('is instance of SVG.Gradient', function() {
expect(radialGradient instanceof SVG.Gradient).toBeTruthy()
})
it('has type of radial', function() {
expect(radialGradient.type).toBe('radialGradient') // actually it should be 'radial'. see #606
})
})
describe('with node that has no matching svg.js class', function() {
it('wraps the node in the base SVG.Element class', function() {
var desc = SVG.get('inlineSVG').select('desc').first()
expect(desc instanceof SVG.Element).toBeTruthy()
})
})
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 | 2 | describe('Arrange', function() {
var e1, e2, e3
beforeEach(function() {
draw.clear()
e1 = draw.rect(100,100).move(10,10).attr('id', 'e1')
e2 = draw.ellipse(100,100).move(20,20).attr('id', 'e2')
e3 = draw.line(0,0,100,100).move(30,30).attr('id', 'e3')
})
describe('siblings()', function() {
it('returns all siblings of targeted element', function() {
expect(e1.siblings().length).toBe(3+parserInDoc)
expect(parser.concat([e1,e2,e3])).toEqual(e2.siblings())
})
})
describe('position()', function() {
it('returns the index position within it\'s parent', function() {
expect(e1.siblings().length).toBe(3+parserInDoc)
expect(e1.position()).toBe(0+parserInDoc)
expect(e2.position()).toBe(1+parserInDoc)
expect(e3.position()).toBe(2+parserInDoc)
})
})
describe('next()', function() {
it('returns the next sibling within the parent element', function() {
expect(e1.next()).toBe(e2)
expect(e2.next()).toBe(e3)
expect(e3.next()).toBe(undefined)
})
})
describe('previous()', function() {
it('returns the previous sibling within the parent element', function() {
expect(e1.previous()).toBe(parser[0])
expect(e2.previous()).toBe(e1)
expect(e3.previous()).toBe(e2)
})
})
describe('forward()', function() {
it('returns the element itself', function() {
expect(e1.forward()).toBe(e1)
})
it('moves the element one step forward within its parent', function() {
e1.forward()
expect(e1.position()).toBe(1+parserInDoc)
expect(e2.position()).toBe(0+parserInDoc)
expect(e3.position()).toBe(2+parserInDoc)
})
it('keeps the last element at the same position', function() {
e3.forward()
expect(e3.position()).toBe(2+parserInDoc)
})
it('keeps the defs on top of the stack', function() {
draw.defs()
e3.forward()
expect(draw.node.childNodes[2+parserInDoc]).toBe(e3.node)
expect(draw.node.childNodes[3+parserInDoc]).toBe(draw.defs().node)
})
})
describe('backward()', function() {
it('returns the element itself', function() {
if(parserInDoc){
expect(parser[0].backward()).toBe(parser[0])
}else{
expect(e1.backward()).toBe(e1)
}
})
it('moves the element one step backwards within its parent', function() {
e3.backward()
expect(e1.position()).toBe(0+parserInDoc)
expect(e2.position()).toBe(2+parserInDoc)
expect(e3.position()).toBe(1+parserInDoc)
})
it('keeps the first element at the same position', function() {
e3.backward()
expect(e1.position()).toBe(0+parserInDoc)
})
})
describe('front()', function() {
it('returns the element itself', function() {
expect(e3.front()).toBe(e3)
})
it('moves the element to the top of the stack within its parent', function() {
e1.front()
expect(e1.position()).toBe(2+parserInDoc)
expect(e2.position()).toBe(0+parserInDoc)
expect(e3.position()).toBe(1+parserInDoc)
})
it('keeps the last element at the same position', function() {
e3.front()
expect(e3.position()).toBe(2+parserInDoc)
})
it('keeps the defs on top of the stack', function() {
e1.front()
expect(draw.node.childNodes[2+parserInDoc]).toBe(e1.node)
expect(draw.node.childNodes[3+parserInDoc]).toBe(draw.defs().node)
})
})
describe('back()', function() {
it('returns the element itself', function() {
expect(e3.back()).toBe(e3)
})
it('moves the element to the bottom of the stack within its parent', function() {
e3.back()
expect(e1.position()).toBe(1+parserInDoc)
expect(e2.position()).toBe(2+parserInDoc)
expect(e3.position()).toBe(0)
})
it('keeps the first element at the same position', function() {
e1.back()
expect(e1.position()).toBe(0)
})
})
describe('before()', function() {
it('returns the targeted element itself', function() {
expect(e3.before(e1)).toBe(e3)
})
it('inserts a given element before the targeted element', function() {
e3.before(e1)
expect(e1.position()).toBe(1+parserInDoc)
expect(e2.position()).toBe(0+parserInDoc)
expect(e3.position()).toBe(2+parserInDoc)
})
it('moves elements between containers', function() {
var group = draw.group()
, e4 = group.rect(80,120)
, e5 = group.rect(80,120)
, e6 = group.rect(80,120)
e2.before(e5)
expect(e1.position()).toBe(0+parserInDoc)
expect(e2.position()).toBe(2+parserInDoc)
expect(e3.position()).toBe(3+parserInDoc)
expect(e5.position()).toBe(1+parserInDoc)
})
})
describe('after()', function() {
it('returns the targeted element itself', function() {
expect(e3.after(e1)).toBe(e3)
})
it('inserts a given element after the targeted element', function() {
e3.after(e1)
expect(e1.position()).toBe(2+parserInDoc)
expect(e2.position()).toBe(0+parserInDoc)
expect(e3.position()).toBe(1+parserInDoc)
})
it('moves elements between containers', function() {
var group = draw.group()
, e4 = group.rect(80,120)
, e5 = group.rect(80,120)
, e6 = group.rect(80,120)
e2.after(e5)
expect(e1.position()).toBe(0+parserInDoc)
expect(e2.position()).toBe(1+parserInDoc)
expect(e3.position()).toBe(3+parserInDoc)
expect(e5.position()).toBe(2+parserInDoc)
})
})
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 | 2 | describe('Array', function () {
var array, arr1, arr2
it('parses a matrix array correctly to string', function() {
array = new SVG.Array([ .343, .669, .119, 0, 0
, .249, -.626, .130, 0, 0
, .172, .334, .111, 0, 0
, .000, .000, .000, 1, -0 ])
expect(array + '').toBe('0.343 0.669 0.119 0 0 0.249 -0.626 0.13 0 0 0.172 0.334 0.111 0 0 0 0 0 1 0')
})
it('parses space seperated string and converts it to array', function() {
expect((new SVG.Array('1 2 3 4')).value).toEqual([1,2,3,4])
})
it('parses comma seperated string and converts it to array', function() {
expect((new SVG.Array('1,2,3,4')).value).toEqual([1,2,3,4])
})
describe('reverse()', function() {
it('reverses the array', function() {
array = new SVG.Array([1 ,2 ,3, 4, 5]).reverse()
expect(array.value).toEqual([5, 4, 3, 2, 1])
})
it('returns itself', function() {
array = new SVG.Array()
expect(array.reverse()).toBe(array)
})
})
describe('clone()', function() {
it('creates a deep clone of the array', function() {
array = new SVG.Array([1, 2, 3, 4, 5])
clone = array.clone()
expect(array).toEqual(clone)
expect(array).not.toBe(clone)
array = new SVG.Array([[1,2], [3, 4], [5]])
clone = array.clone()
expect(array).toEqual(array)
for(var i = 0, len = array.value.length; i; ++i){
expect(array[i]).not.toBe(clone[i])
}
})
it('also works with PointArray', function() {
array = new SVG.PointArray([1,2,3,4,5,6])
clone = array.clone()
expect(array).toEqual(clone)
expect(array).not.toBe(clone)
for(var i = 0, len = array.value.length; i; ++i){
expect(array[i]).not.toBe(clone[i])
}
})
it('also works with PathArray', function() {
array = new SVG.PathArray([['M',1,2],['L',3,4],['L',5,6]])
clone = array.clone()
expect(array).toEqual(clone)
expect(array).not.toBe(clone)
for(var i = 0, len = array.value.length; i; ++i){
expect(array[i]).not.toBe(clone[i])
}
})
})
describe('morph()', function() {
it('adds entries so that destination array has equal length', function() {
arr1 = new SVG.Array([1,2,3,4,5])
arr2 = new SVG.Array([1,2,3,4])
arr1.morph(arr2)
expect(arr1.destination.length).toBe(arr1.value.length)
})
it('does the same the other way round', function() {
arr1 = new SVG.Array([1,2,3,4])
arr2 = new SVG.Array([1,2,3,4,5])
arr1.morph(arr2)
expect(arr1.destination.length).toBe(arr1.value.length)
})
})
describe('settle()', function() {
it('cleans up any duplicate value', function() {
array = new SVG.Array([1,2,3,4,5,4,3,2,1])
expect(array.settle().sort()).toEqual([1,2,3,4,5].sort())
})
})
describe('at()', function() {
beforeEach(function() {
arr1 = new SVG.Array([1,2,3,4])
arr2 = new SVG.Array([2,3,4,5])
})
it('returns a new array instance', function() {
arr1.morph(arr2)
start = arr1.at(0)
end = arr1.at(1)
expect(start instanceof SVG.Array).toBeTruthy()
expect(start).not.toBe(arr1)
expect(end instanceof SVG.Array).toBeTruthy()
expect(end).not.toBe(arr2)
})
it('morphs all values of the array', function() {
arr1.morph(arr2)
expect(arr1.at(0.5).value).toEqual([1.5, 2.5, 3.5, 4.5])
})
it('returns itself if no destination was specified', function() {
expect(arr1.at(0.5)).toBe(arr1)
})
})
})
describe('PointArray', function () {
it('parses a string to a point array', function() {
var array = new SVG.PointArray('0,1 -.05,7.95 1000.0001,-200.222')
expect(array.valueOf()).toEqual([[0, 1], [-0.05, 7.95], [1000.0001, -200.222]])
})
it('parses a points array correctly to string', function() {
var array = new SVG.PointArray([[0,.15], [-100,-3.141592654], [50,100]])
expect(array + '').toBe('0,0.15 -100,-3.141592654 50,100')
})
it('parses a flat array of x/y coordinates to a point array', function() {
var array = new SVG.PointArray([1,4, 5,68, 12,24])
expect(array.value).toEqual([[1,4], [5,68], [12,24]])
})
it('parses points with space delimitered x/y coordinates', function() {
var array = new SVG.PointArray('221.08 191.79 0.46 191.79 0.46 63.92 63.8 0.46 284.46 0.46 284.46 128.37 221.08 191.79')
expect(array + '').toBe('221.08,191.79 0.46,191.79 0.46,63.92 63.8,0.46 284.46,0.46 284.46,128.37 221.08,191.79')
})
it('parses points with comma delimitered x/y coordinates', function() {
var array = new SVG.PointArray('221.08,191.79,0.46,191.79,0.46,63.92,63.8,0.46,284.46,0.46,284.46,128.37,221.08,191.79')
expect(array + '').toBe('221.08,191.79 0.46,191.79 0.46,63.92 63.8,0.46 284.46,0.46 284.46,128.37 221.08,191.79')
})
it('parses points with comma and space delimitered x/y coordinates', function() {
var array = new SVG.PointArray('221.08, 191.79, 0.46, 191.79, 0.46, 63.92, 63.8, 0.46, 284.46, 0.46, 284.46, 128.37, 221.08, 191.79')
expect(array + '').toBe('221.08,191.79 0.46,191.79 0.46,63.92 63.8,0.46 284.46,0.46 284.46,128.37 221.08,191.79')
})
it('parses points with space and comma delimitered x/y coordinates', function() {
var array = new SVG.PointArray('221.08 ,191.79 ,0.46 ,191.79 ,0.46 ,63.92 ,63.8 ,0.46 ,284.46 ,0.46 ,284.46 ,128.37 ,221.08 ,191.79')
expect(array + '').toBe('221.08,191.79 0.46,191.79 0.46,63.92 63.8,0.46 284.46,0.46 284.46,128.37 221.08,191.79')
})
it('parses points with redundant spaces at the end', function() {
var array = new SVG.PointArray('2176.6,1708.8 2176.4,1755.8 2245.8,1801.5 2297,1787.8 ')
expect(array + '').toBe('2176.6,1708.8 2176.4,1755.8 2245.8,1801.5 2297,1787.8')
})
it('parses points with space delimitered x/y coordinates - even with leading or trailing space', function() {
var array = new SVG.PointArray(' 1 2 3 4 ')
expect(array + '').toBe('1,2 3,4')
})
it('parses odd number of points with space delimitered x/y coordinates and silently remove the odd point', function() {
// this is according to spec: https://svgwg.org/svg2-draft/shapes.html#DataTypePoints
var array = new SVG.PointArray('1 2 3')
expect(array + '').toBe('1,2')
})
it('parses odd number of points in a flat array of x/y coordinates and silently remove the odd point', function() {
// this is according to spec: https://svgwg.org/svg2-draft/shapes.html#DataTypePoints
var array = new SVG.PointArray([1, 2, 3])
expect(array.value).toEqual([[1,2]])
})
describe('size()', function() {
it('correctly sizes the points over the whole area', function() {
var array = new SVG.PointArray([10, 10, 20, 20, 30, 30])
expect(array.size(60, 60).valueOf()).toEqual([[10,10], [40, 40], [70, 70]])
})
it('let coordinates untouched when width/height is zero', function() {
var array = new SVG.PointArray([10, 10, 10, 20, 10, 30])
expect(array.size(60, 60).valueOf()).toEqual([[10,10], [10, 40], [10, 70]])
array = new SVG.PointArray([10, 10, 20, 10, 30, 10])
expect(array.size(60, 60).valueOf()).toEqual([[10,10], [40, 10], [70, 10]])
})
})
describe('at()', function() {
var arr1, arr2
beforeEach(function() {
arr1 = new SVG.PointArray([[1,2],[3,4]])
arr2 = new SVG.Array([[2,3],[4,5]])
})
it('returns a new array instance', function() {
arr1.morph(arr2)
start = arr1.at(0)
end = arr1.at(1)
expect(start instanceof SVG.PointArray).toBeTruthy()
expect(start).not.toBe(arr1)
expect(end instanceof SVG.PointArray).toBeTruthy()
expect(end).not.toBe(arr2)
})
it('morphs all values of the array', function() {
arr1.morph(arr2)
expect(arr1.at(0.5).value).toEqual([[1.5, 2.5], [3.5, 4.5]])
})
it('returns itself if no destination was specified', function() {
expect(arr1.at(0.5)).toBe(arr1)
})
})
})
describe('PathArray', function () {
var p1, p2, p3, p4, p5, p6, p7
beforeEach(function() {
p1 = new SVG.PathArray('m10 10 h 80 v 80 h -80 l 300 400 z')
p2 = new SVG.PathArray('m10 80 c 40 10 65 10 95 80 s 150 150 180 80 t 300 300 q 52 10 95 80 z')
p3 = new SVG.PathArray('m80 80 A 45 45, 0, 0, 0, 125 125 L 125 80 z')
p4 = new SVG.PathArray('M215.458,245.23c0,0,77.403,0,94.274,0S405,216.451,405,138.054S329.581,15,287.9,15c-41.68,0-139.924,0-170.688,0C86.45,15,15,60.65,15,134.084c0,73.434,96.259,112.137,114.122,112.137C146.984,246.221,215.458,245.23,215.458,245.23z')
p5 = new SVG.PathArray(
'M10 10-45-30.5.5 .89L2e-2.5.5.5-.5C.5.5.5.5.5.5L-3-4z'
)
})
it('converts to absolute values', function() {
expect(p1.toString()).toBe('M10 10H90V90H10L310 490Z ')
expect(p2.toString()).toBe('M10 80C50 90 75 90 105 160S255 310 285 240T585 540Q637 550 680 620Z ')
expect(p3.toString()).toBe('M80 80A45 45 0 0 0 125 125L125 80Z ')
expect(p4.toString()).toBe('M215.458 245.23C215.458 245.23 292.861 245.23 309.73199999999997 245.23S405 216.451 405 138.054S329.581 15 287.9 15C246.21999999999997 15 147.97599999999997 15 117.21199999999999 15C86.45 15 15 60.65 15 134.084C15 207.518 111.259 246.221 129.122 246.221C146.984 246.221 215.458 245.23 215.458 245.23Z ')
})
it('parses difficult syntax correctly', function() {
expect(p5.toString()).toBe('M10 10L-45 -30.5L0.5 0.89L0.02 0.5L0.5 -0.5C0.5 0.5 0.5 0.5 0.5 0.5L-3 -4Z ')
})
it('parses flat arrays correctly', function() {
p6 = new SVG.PathArray([ 'M', 0, 0, 'L', 100, 100, 'z' ])
expect(p6.toString()).toBe('M0 0L100 100Z ')
})
it('parses nested arrays correctly', function() {
p7 = new SVG.PathArray([ ['M', 0, 0], ['L', 100, 100], ['z'] ])
expect(p7.toString()).toBe('M0 0L100 100Z ')
})
// this test is designed to cover a certain line but it doesnt work because of #608
it('returns the valueOf when PathArray is given', function() {
var p = new SVG.PathArray('m10 10 h 80 v 80 h -80 l 300 400 z')
expect((new SVG.PathArray(p)).value).toEqual(p.value)
})
it('can handle all formats which can be used', function() {
// when no command is specified after move, line is used automatically (specs say so)
expect(new SVG.PathArray('M10 10 80 80 30 30 Z').toString()).toBe('M10 10L80 80L30 30Z ')
// parsing can handle 0.5.3.3.2 stuff
expect(new SVG.PathArray('M10 10L.5.5.3.3Z').toString()).toBe('M10 10L0.5 0.5L0.3 0.3Z ')
})
describe('move()', function() {
it('moves all points in a straight path', function() {
expect(p1.move(100,200).toString()).toBe('M100 200H180V280H100L400 680Z ')
})
it('moves all points in a curved path', function() {
expect(p2.move(100,200).toString()).toBe('M100 200C140 210 165 210 195 280S345 430 375 360T675 660Q727 670 770 740Z ')
})
it('moves all points in a arc path', function() {
expect(p3.move(100,200).toString()).toBe('M100 200A45 45 0 0 0 145 245L145 200Z ')
})
})
describe('size()', function() {
it('resizes all points in a straight path', function() {
expect(p1.size(600,200).toString()).toBe('M10 10H170V43.333333333333336H10L610 210Z ')
})
it('resizes all points in a curved path', function() {
expect(p2.size(600,200).toString()).toBe('M10 80C45.82089552238806 83.70370370370371 68.2089552238806 83.70370370370371 95.07462686567165 109.62962962962963S229.40298507462686 165.1851851851852 256.2686567164179 139.25925925925927T524.9253731343283 250.37037037037038Q571.4925373134329 254.07407407407408 610 280Z ')
})
it('resizes all points in a arc path', function() {
var expected = [
['M', 80, 80],
['A', 600, 200, 0, 0, 0, 680, 280],
['L', 680, 80],
['Z']
]
var toBeTested = p3.size(600,200).value
for(var i in toBeTested) {
expect(toBeTested[i].shift().toUpperCase()).toBe(expected[i].shift().toUpperCase())
for(var j in toBeTested[i]) {
expect(toBeTested[i][j]).toBeCloseTo(expected[i][j])
}
}
})
})
describe('equalCommands()', function() {
it('return true if the passed path array use the same commands', function() {
var pathArray1 = new SVG.PathArray('m -1500,-478 a 292,195 0 0 1 262,205 l -565,319 c 0,0 -134,-374 51,-251 185,122 251,-273 251,-273 z')
, pathArray2 = new SVG.PathArray('m -680, 527 a 292,195 0 0 1 262,205 l -565,319 c 0,0 -134,-374 51,-251 185,122 251,-273 251,-273 z')
expect(pathArray1.equalCommands(pathArray2)).toBe(true)
})
it('return false if the passed path array does not use the same commands', function() {
var pathArray1 = new SVG.PathArray('m -1500,-478 a 292,195 0 0 1 262,205 l -565,319 c 0,0 -134,-374 51,-251 185,122 251,-273 251,-273 z')
, pathArray2 = new SVG.PathArray('m - 663, 521 c 147,178 118,-25 245,210 l -565,319 c 0,0 -134,-374 51,-251 185,122 268,-278 268,-278 z')
expect(pathArray1.equalCommands(pathArray2)).toBe(false)
})
})
describe('morph()', function() {
it('should set the attribute destination to the passed path array when it have the same comands as this path array', function() {
var pathArray1 = new SVG.PathArray('m -1500,-478 a 292,195 0 0 1 262,205 l -565,319 c 0,0 -134,-374 51,-251 185,122 251,-273 251,-273 z')
, pathArray2 = new SVG.PathArray('m -680, 527 a 292,195 0 0 1 262,205 l -565,319 c 0,0 -134,-374 51,-251 185,122 251,-273 251,-273 z')
pathArray1.morph(pathArray2)
expect(pathArray1.destination).toEqual(pathArray2)
})
it('should set the attribute destination to null when the passed path array does not have the same comands as this path array', function() {
var pathArray1 = new SVG.PathArray('m -1500,-478 a 292,195 0 0 1 262,205 l -565,319 c 0,0 -134,-374 51,-251 185,122 251,-273 251,-273 z')
, pathArray2 = new SVG.PathArray('m - 663, 521 c 147,178 118,-25 245,210 l -565,319 c 0,0 -134,-374 51,-251 185,122 268,-278 268,-278 z')
pathArray1.morph(pathArray2)
expect(pathArray1.destination).toBeNull()
})
})
describe('at()', function() {
it('returns a morphed path array at a given position', function() {
var pathArray1 = new SVG.PathArray("M 63 25 A 15 15 0 0 1 73 40 A 15 15 0 0 1 61 53 C 49 36 50 59 50 59 L 33 55 Z")
, pathArray2 = new SVG.PathArray("M 132 40 A 15 15 0 0 1 141 54 A 15 15 0 0 1 130 67 C 118 51 119 73 119 73 L 103 69 Z")
, morphedPathArray = pathArray1.morph(pathArray2).at(0.5)
, sourceArray = pathArray1.value, destinationArray = pathArray1.destination.value
, morphedArray = morphedPathArray.value
, i, il, j, jl
expect(morphedArray.length).toBe(sourceArray.length)
// For all the commands
for(i = 0, il = sourceArray.length; i < il; i++) {
// Expect the current command to be the same
expect(morphedArray[i][0]).toBe(sourceArray[i][0])
expect(morphedArray[i].length).toBe(sourceArray[i].length)
// For all the parameters of the current command
for(j = 1, jl = sourceArray[i].length; j < jl; j++) {
expect(morphedArray[i][j]).toBe((sourceArray[i][j] + destinationArray[i][j]) / 2)
}
}
})
it('should interpolate flags and booleans as fractions between zero and one, with any non-zero value considered to be a value of one/true', function() {
// Only the Elliptical arc command use flags, it has the following form:
// A rx ry x-axis-rotation large-arc-flag sweep-flag x y
var pathArray1 = new SVG.PathArray('M 13 13 A 25 37 0 0 1 43 25')
, pathArray2 = new SVG.PathArray('M 101 55 A 25 37 0 1 0 130 67')
, morphedPathArray
pathArray1.morph(pathArray2)
// The morphedPathArray.value contain 2 commands: [['M', ...], ['A', ...]]
// Elliptical arc command in a path array followed by corresponding indexes:
// ['A', rx, ry, x-axis-rotation, large-arc-flag, sweep-flag, x, y]
// 0 1 2 3 4 5 6 7
morphedPathArray = pathArray1.at(0)
expect(morphedPathArray.value[1][4]).toBe(0)
expect(morphedPathArray.value[1][5]).toBe(1)
morphedPathArray = pathArray1.at(0.5)
expect(morphedPathArray.value[1][4]).toBe(1)
expect(morphedPathArray.value[1][5]).toBe(1)
morphedPathArray = pathArray1.at(1)
expect(morphedPathArray.value[1][4]).toBe(1)
expect(morphedPathArray.value[1][5]).toBe(0)
})
it('return itself if the destination attribute is null', function(){
var pathArray = new SVG.PathArray('M 13 13 A 25 37 0 0 1 43 25')
pathArray.destination = null
expect(pathArray.at(0.45)).toBe(pathArray)
})
})
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | 2 | describe('Bare', function() {
describe('element()', function() {
var element
beforeEach(function() {
element = draw.element('rect')
})
it('creates an instance of SVG.Bare', function() {
expect(element instanceof SVG.Bare).toBeTruthy()
})
it('creates element in called parent', function() {
expect(element.parent()).toBe(draw)
})
it('inherits from given parent', function() {
expect(draw.element('g', SVG.Container).rect).toBeTruthy()
expect(draw.element('g', SVG.Container).group).toBeTruthy()
})
})
describe('words()', function() {
it('inserts plain text in a node', function() {
var element = draw.element('title').words('These are some words.').id(null)
var result = element.svg()
expect(
result == '<title>These are some words.</title>'
|| result == '<title xmlns="http://www.w3.org/2000/svg">These are some words.</title>'
).toBe(true)
})
it('removes all nodes before adding words', function() {
var element = draw.element('title').words('These are some words.').id(null)
element.words('These are some words.')
var result = element.svg()
expect(
result == '<title>These are some words.</title>'
|| result == '<title xmlns="http://www.w3.org/2000/svg">These are some words.</title>'
).toBe(true)
})
})
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 | 2 | describe('Box', function() {
it('creates a new instance without passing anything', function() {
var box = new SVG.Box
expect(box instanceof SVG.Box).toBe(true)
expect(box).toEqual(jasmine.objectContaining({
x:0, y:0, cx:0, cy:0, width:0, height:0
}))
})
it('creates a new instance with 4 arguments given', function() {
var box = new SVG.Box(10, 20, 100, 50)
expect(box instanceof SVG.Box).toBe(true)
expect(box).toEqual(jasmine.objectContaining({
x:10, y:20, cx:60, cy:45, width:100, height:50
}))
})
it('creates a new instance with object given', function() {
var box = new SVG.Box({x:10, y:20, width: 100, height:50})
expect(box instanceof SVG.Box).toBe(true)
expect(box).toEqual(jasmine.objectContaining({
x:10, y:20, cx:60, cy:45, width:100, height:50
}))
})
describe('merge()', function() {
it('merges various bounding boxes', function() {
var box1 = new SVG.Box(50, 50, 100, 100)
var box2 = new SVG.Box(300, 400, 100, 100)
var box3 = new SVG.Box(500, 100, 100, 100)
var merged = box1.merge(box2).merge(box3)
expect(merged).toEqual(jasmine.objectContaining({
x: 50, y: 50, cx: 325, cy: 275, width: 550, height: 450
}))
})
it('returns a new instance', function() {
var box1 = new SVG.Box(50, 50, 100, 100)
var box2 = new SVG.Box(300, 400, 100, 100)
var merged = box1.merge(box2)
expect(box1).not.toBe(merged)
expect(box2).not.toBe(merged)
expect(merged instanceof SVG.Box).toBe(true)
})
})
describe('transform()', function() {
it('transforms the box with given matrix', function() {
var box1 = new SVG.Box(50, 50, 100, 100).transform(new SVG.Matrix(1,0,0,1,20,20))
var box2 = new SVG.Box(50, 50, 100, 100).transform(new SVG.Matrix(2,0,0,2,0,0))
var box3 = new SVG.Box(-200, -200, 100, 100).transform(new SVG.Matrix(1,0,0,1,-20,-20))
expect(box1).toEqual(jasmine.objectContaining({
x: 70, y: 70, cx: 120, cy: 120, width: 100, height: 100
}))
expect(box2).toEqual(jasmine.objectContaining({
x: 100, y: 100, cx: 200, cy: 200, width: 200, height: 200
}))
expect(box3).toEqual(jasmine.objectContaining({
x: -220, y: -220, cx: -170, cy: -170, width: 100, height: 100
}))
})
})
})
describe('BBox', function() {
afterEach(function() {
draw.clear()
})
it('creates a new instance from an element', function() {
var rect = draw.rect(100, 100).move(100, 25)
var box = new SVG.BBox(rect)
expect(box).toEqual(jasmine.objectContaining({
x: 100, y: 25, cx: 150, cy: 75, width: 100, height: 100
}))
})
describe('merge()', function() {
it('returns an instance of SVG.BBox', function() {
var box1 = new SVG.BBox(50, 50, 100, 100)
var box2 = new SVG.BBox(300, 400, 100, 100)
var merged = box1.merge(box2)
expect(merged instanceof SVG.BBox).toBe(true)
})
})
})
describe('TBox', function() {
afterEach(function() {
draw.clear()
})
it('should map to RBox and be removed in 3.x', function() {
var rect = draw.rect(100, 100).move(100, 25).stroke({width:0})
var tbox = rect.tbox()
expect(tbox.x).toBe(100)
expect(tbox.y).toBeCloseTo(25)
rect.transform({ scale: 1.5 })
tbox = rect.tbox()
expect(tbox.x).toBe(75)
expect(tbox.y).toBe(0)
rect.transform({ skewX: 5 })
tbox = rect.tbox()
expect(tbox.x|0).toBe(68)
expect(tbox.y|0).toBe(0)
})
})
describe('RBox', function() {
afterEach(function() {
draw.clear()
})
it('creates a new instance from an element', function() {
var rect = draw.rect(100, 100).move(100, 25).stroke({width:0})
var box = new SVG.RBox(rect).transform(rect.doc().screenCTM().inverse()).addOffset()
expect(window.roundBox(box)).toEqual(jasmine.objectContaining({
x: 100, y: 25, cx: 150, cy: 75, width: 100, height: 100
}))
})
describe('merge()', function() {
it('returns an instance of SVG.RBox', function() {
var box1 = new SVG.RBox(50, 50, 100, 100)
var box2 = new SVG.RBox(300, 400, 100, 100)
var merged = box1.merge(box2)
expect(merged instanceof SVG.RBox).toBe(true)
})
})
})
describe('Boxes', function() {
var rect, nested, offset
beforeEach(function() {
offset = draw.screenCTM()
draw.viewbox(100,100, 200, 200)
nested = draw.nested().size(200, 200).move(100,100).viewbox(0, 0, 100, 100)
rect = nested.rect(50, 180).stroke({width:0}).move(25, 90).scale(2, 0, 0).transform({x:10, y:10}, true)
})
afterEach(function() {
draw.clear().attr('viewBox', null)
})
describe('bbox()', function() {
it('returns an instance of SVG.BBox', function() {
expect(rect.bbox() instanceof SVG.BBox).toBeTruthy()
})
it('matches the size of the target element, ignoring transformations', function() {
var box = rect.bbox()
expect(box).toEqual(jasmine.objectContaining({
x: 25, y: 90, cx: 50, cy: 180, width: 50, height: 180
}))
})
it('returns a box even if the element is not in the dom', function() {
var line = new SVG.Line().plot(0, 0, 50, 50)
var box = line.bbox()
expect(box).toEqual(jasmine.objectContaining({
x: 0, y: 0, width: 50, height: 50
}))
expect('Should not result into infinite loop').toBe('Should not result into infinite loop')
})
it('returns a box even if the element is not in the dom and invisible', function() {
var line = new SVG.Line().plot(0, 0, 50, 50).hide()
var box = line.bbox()
expect(box).toEqual(jasmine.objectContaining({
x: 0, y: 0, width: 50, height: 50
}))
expect('Should not result into infinite loop').toBe('Should not result into infinite loop')
})
})
describe('rbox()', function() {
it('returns an instance of SVG.RBox', function() {
expect(rect.rbox() instanceof SVG.RBox).toBeTruthy()
})
it('returns the elements box in absolute screen coordinates by default', function() {
var box = rect.rbox()
expect(window.roundBox(box)).toEqual(jasmine.objectContaining(window.roundBox({
x: 70 + offset.e, y: 200 + offset.f, width: 100, height: 360
})))
})
it('returns the elements box in coordinates of given element (doc)', function() {
var box = rect.rbox(draw)
expect(window.roundBox(box)).toEqual(jasmine.objectContaining({
x: 240, y: 500, width: 200, height: 720
}))
})
it('returns the elements box in coordinates of given element (nested)', function() {
var box = rect.rbox(nested)
expect(window.roundBox(box)).toEqual(jasmine.objectContaining({
x: 70, y: 200, width: 100, height: 360
}))
})
})
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 | 2 | describe('Circle', function() {
var circle
beforeEach(function() {
circle = draw.circle(240)
})
afterEach(function() {
draw.clear()
})
describe('x()', function() {
it('returns the value of x without an argument', function() {
expect(circle.x()).toBe(0)
})
it('sets the value of x with the first argument', function() {
circle.x(123)
var box = circle.bbox()
expect(box.x).toBeCloseTo(123)
})
})
describe('y()', function() {
it('returns the value of y without an argument', function() {
expect(circle.y()).toBe(0)
})
it('sets the value of cy with the first argument', function() {
circle.y(345)
var box = circle.bbox()
expect(box.y).toBe(345)
})
})
describe('cx()', function() {
it('returns the value of cx without an argument', function() {
expect(circle.cx()).toBe(120)
})
it('sets the value of cx with the first argument', function() {
circle.cx(123)
var box = circle.bbox()
expect(box.cx).toBe(123)
})
})
describe('cy()', function() {
it('returns the value of cy without an argument', function() {
expect(circle.cy()).toBe(120)
})
it('sets the value of cy with the first argument', function() {
circle.cy(345)
var box = circle.bbox()
expect(box.cy).toBe(345)
})
})
describe('radius()', function() {
it('sets the r attribute with the first argument', function() {
circle.radius(10)
expect(circle.node.getAttribute('r')).toBe('10')
})
})
describe('rx()', function() {
it('sets the r attribute with the first argument', function() {
circle.rx(11)
expect(circle.node.getAttribute('r')).toBe('11')
})
it('gets the r attribute without and argument', function() {
circle.rx()
expect(circle.node.getAttribute('r')).toBe('120')
})
})
describe('ry()', function() {
it('sets the r attribute with the first argument', function() {
circle.ry(12)
expect(circle.node.getAttribute('r')).toBe('12')
})
it('gets the r attribute without and argument', function() {
circle.ry()
expect(circle.node.getAttribute('r')).toBe('120')
})
})
describe('move()', function() {
it('sets the x and y position', function() {
circle.move(123, 456)
var box = circle.bbox()
expect(box.x).toBeCloseTo(123)
expect(box.y).toBe(456)
})
})
describe('dx()', function() {
it('moves the x positon of the element relative to the current position', function() {
circle.move(50, 60)
circle.dx(100)
expect(circle.node.getAttribute('cx')).toBe('270')
})
})
describe('dy()', function() {
it('moves the y positon of the element relative to the current position', function() {
circle.move(50, 60)
circle.dy(120)
expect(circle.node.getAttribute('cy')).toBe('300')
})
})
describe('dmove()', function() {
it('moves the x and y positon of the element relative to the current position', function() {
circle.move(50,60)
circle.dmove(80, 25)
expect(circle.node.getAttribute('cx')).toBe('250')
expect(circle.node.getAttribute('cy')).toBe('205')
})
})
describe('center()', function() {
it('sets the cx and cy position', function() {
circle.center(321,567)
var box = circle.bbox()
expect(box.cx).toBe(321)
expect(box.cy).toBe(567)
})
})
describe('width()', function() {
it('sets the width and height of the element', function() {
circle.width(82)
expect(circle.node.getAttribute('r')).toBe('41')
})
it('gets the width and height of the element if the argument is null', function() {
expect((circle.width() / 2).toString()).toBe(circle.node.getAttribute('r'))
})
})
describe('height()', function() {
it('sets the height and width of the element', function() {
circle.height(1236)
expect(circle.node.getAttribute('r')).toBe('618')
})
it('gets the height and width of the element if the argument is null', function() {
expect((circle.height() / 2).toString()).toBe(circle.node.getAttribute('r'))
})
})
describe('size()', function() {
it('defines the r of the element', function() {
circle.size(987)
expect(circle.node.getAttribute('r')).toBe((987 / 2).toString())
})
})
describe('scale()', function() {
it('should scale the element universally with one argument', function() {
var box = circle.scale(2).rbox()
expect(box.width).toBe(circle.attr('r') * 2 * 2)
expect(box.height).toBe(circle.attr('r') * 2 * 2)
})
it('should scale the element over individual x and y axes with two arguments', function() {
var box = circle.scale(2, 3.5).rbox()
expect(box.width).toBe(circle.attr('r') * 2 * 2)
expect(box.height).toBe(circle.attr('r') * 2 * 3.5)
})
})
describe('translate()', function() {
it('sets the translation of an element', function() {
circle.transform({ x: 12, y: 12 })
expect(window.matrixStringToArray(circle.node.getAttribute('transform'))).toEqual([1,0,0,1,12,12])
})
})
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | 2 | describe('ClipPath', function() {
var rect, circle
beforeEach(function() {
rect = draw.rect(100,100)
circle = draw.circle(100).move(50, 50)
rect.clipWith(circle)
})
afterEach(function() {
draw.clear()
})
it('moves the clipping element to a new clip node', function() {
expect(circle.parent() instanceof SVG.ClipPath).toBe(true)
})
it('creates the clip node in the defs node', function() {
expect(circle.parent().parent()).toBe(draw.defs())
})
it('sets the "clip-path" attribute on the cliped element with the clip id', function() {
expect(rect.attr('clip-path')).toBe('url("#' + circle.parent().attr('id') + '")')
})
it('references the clip element in the masked element', function() {
expect(rect.clipper).toBe(circle.parent())
})
it('references the clipped element in the clipPath target list', function() {
expect(rect.clipper.targets.indexOf(rect) > -1).toBe(true)
})
it('reuses clip element when clip was given', function() {
var clip = rect.clipper
expect(draw.rect(100,100).clipWith(clip).clipper).toBe(clip)
})
it('unclips all clipped elements when being removed', function() {
rect.clipper.remove()
expect(rect.attr('clip-path')).toBe(undefined)
})
describe('unclip()', function() {
it('clears the "clip-path" attribute on the clipped element', function() {
rect.unclip()
expect(rect.attr('clip-path')).toBe(undefined)
})
it('removes the reference to the clipping element', function() {
rect.unclip()
expect(rect.clipper).toBe(undefined)
})
it('returns the clipPath element', function() {
expect(rect.unclip()).toBe(rect)
})
})
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | 2 | describe('Color', function() {
var color
beforeEach(function() {
color = new SVG.Color({ r: 0, g: 102, b: 255 })
})
it('correclty parses a rgb string', function() {
color = new SVG.Color('rgb(255,0,128)')
expect(color.r).toBe(255)
expect(color.g).toBe(0)
expect(color.b).toBe(128)
})
it('correclty parses a 3 digit hex string', function() {
color = new SVG.Color('#f06')
expect(color.r).toBe(255)
expect(color.g).toBe(0)
expect(color.b).toBe(102)
})
it('correclty parses a 6 digit hex string', function() {
color = new SVG.Color('#0066ff')
expect(color.r).toBe(0)
expect(color.g).toBe(102)
expect(color.b).toBe(255)
})
describe('toHex()', function() {
it('returns a hex color', function() {
expect(color.toHex()).toBe('#0066ff')
})
})
describe('toRgb()', function() {
it('returns a rgb string color', function() {
expect(color.toRgb()).toBe('rgb(0,102,255)')
})
})
describe('brightness()', function() {
it('returns the percieved brightness value of a color', function() {
expect(color.brightness()).toBe(0.346)
})
})
describe('morph()', function() {
it('prepares the color for morphing', function() {
var destination = new SVG.Color
color.morph(destination)
expect(color.destination).toEqual(destination)
})
})
describe('at()', function() {
it('morphes color to a given position', function() {
var destination = new SVG.Color
var morphed = color.morph(destination).at(0.5)
expect(morphed.r).toBe(0)
expect(morphed.g).toBe(51)
expect(morphed.b).toBe(127)
})
it('morphes color to 1 with higher values', function() {
var destination = new SVG.Color('#fff')
var morphed = color.morph(destination).at(2)
expect(morphed.r).toBe(255)
expect(morphed.g).toBe(255)
expect(morphed.b).toBe(255)
})
it('morphes color to 0 with lower values', function() {
var destination = new SVG.Color('#fff')
var morphed = color.morph(destination).at(-3)
expect(morphed.r).toBe(0)
expect(morphed.g).toBe(102)
expect(morphed.b).toBe(255)
})
it('returns itself when no destination specified', function() {
expect(color.at(0.5)).toBe(color)
})
})
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 | 2 | describe('Container', function() {
beforeEach(function() {
draw.clear()
})
describe('rect()', function() {
it('should increase children by 1', function() {
var initial = draw.children().length
draw.rect(100,100)
expect(draw.children().length).toBe(initial + 1)
})
it('should create a rect', function() {
expect(draw.rect(100,100).type).toBe('rect')
})
it('should create an instance of SVG.Rect', function() {
expect(draw.rect(100,100) instanceof SVG.Rect).toBe(true)
})
it('should be an instance of SVG.Shape', function() {
expect(draw.rect(100,100) instanceof SVG.Shape).toBe(true)
})
it('should be an instance of SVG.Element', function() {
expect(draw.rect(100,100) instanceof SVG.Element).toBe(true)
})
})
describe('ellipse()', function() {
it('should increase children by 1', function() {
var initial = draw.children().length
draw.ellipse(100,100)
expect(draw.children().length).toBe(initial + 1)
})
it('should create an ellipse', function() {
expect(draw.ellipse(100,100).type).toBe('ellipse')
})
it('should create an instance of SVG.Ellipse', function() {
expect(draw.ellipse(100,100) instanceof SVG.Ellipse).toBe(true)
})
it('should be an instance of SVG.Shape', function() {
expect(draw.ellipse(100,100) instanceof SVG.Shape).toBe(true)
})
it('should be an instance of SVG.Element', function() {
expect(draw.ellipse(100,100) instanceof SVG.Element).toBe(true)
})
})
describe('circle()', function() {
it('should increase children by 1', function() {
var initial = draw.children().length
draw.circle(100)
expect(draw.children().length).toBe(initial + 1)
})
it('should create an circle', function() {
expect(draw.circle(100).type).toBe('circle')
})
it('should create an instance of SVG.Circle', function() {
expect(draw.circle(100) instanceof SVG.Circle).toBe(true)
})
it('should be an instance of SVG.Shape', function() {
expect(draw.circle(100) instanceof SVG.Shape).toBe(true)
})
it('should be an instance of SVG.Element', function() {
expect(draw.circle(100) instanceof SVG.Element).toBe(true)
})
})
describe('line()', function() {
it('should increase children by 1', function() {
var initial = draw.children().length
draw.line(0,100,100,0)
expect(draw.children().length).toBe(initial + 1)
})
it('should create a line', function() {
expect(draw.line(0,100,100,0).type).toBe('line')
})
it('should create an instance of SVG.Line', function() {
expect(draw.line(0,100,100,0) instanceof SVG.Line).toBe(true)
})
it('should be an instance of SVG.Shape', function() {
expect(draw.line(0,100,100,0) instanceof SVG.Shape).toBe(true)
})
it('should be an instance of SVG.Element', function() {
expect(draw.line(0,100,100,0) instanceof SVG.Element).toBe(true)
})
})
describe('polyline()', function() {
it('should increase children by 1', function() {
var initial = draw.children().length
draw.polyline('0,0 100,0 100,100 0,100')
expect(draw.children().length).toBe(initial + 1)
})
it('should create a polyline', function() {
expect(draw.polyline('0,0 100,0 100,100 0,100').type).toBe('polyline')
})
it('should be an instance of SVG.Polyline', function() {
expect(draw.polyline('0,0 100,0 100,100 0,100') instanceof SVG.Polyline).toBe(true)
})
it('should be an instance of SVG.Shape', function() {
expect(draw.polyline('0,0 100,0 100,100 0,100') instanceof SVG.Shape).toBe(true)
})
it('should be an instance of SVG.Element', function() {
expect(draw.polyline('0,0 100,0 100,100 0,100') instanceof SVG.Element).toBe(true)
})
})
describe('polygon()', function() {
it('should increase children by 1', function() {
var initial = draw.children().length
draw.polygon('0,0 100,0 100,100 0,100')
expect(draw.children().length).toBe(initial + 1)
})
it('should create a polygon', function() {
expect(draw.polygon('0,0 100,0 100,100 0,100').type).toBe('polygon')
})
it('should be an instance of SVG.Polygon', function() {
expect(draw.polygon('0,0 100,0 100,100 0,100') instanceof SVG.Polygon).toBe(true)
})
it('should be an instance of SVG.Shape', function() {
expect(draw.polygon('0,0 100,0 100,100 0,100') instanceof SVG.Shape).toBe(true)
})
it('should be an instance of SVG.Element', function() {
expect(draw.polygon('0,0 100,0 100,100 0,100') instanceof SVG.Element).toBe(true)
})
})
describe('path()', function() {
it('should increase children by 1', function() {
var initial = draw.children().length
draw.path(svgPath)
expect(draw.children().length).toBe(initial + 1)
})
it('should create a path', function() {
expect(draw.path(svgPath).type).toBe('path')
})
it('should be an instance of SVG.Path', function() {
expect(draw.path(svgPath) instanceof SVG.Path).toBe(true)
})
it('should be an instance of SVG.Shape', function() {
expect(draw.path(svgPath) instanceof SVG.Shape).toBe(true)
})
it('should be an instance of SVG.Element', function() {
expect(draw.path(svgPath) instanceof SVG.Element).toBe(true)
})
})
describe('image()', function() {
it('should increase children by 1', function() {
var initial = draw.children().length
draw.image(imageUrl, 100, 100)
expect(draw.children().length).toBe(initial + 1)
})
it('should create a rect', function() {
expect(draw.image(imageUrl, 100, 100).type).toBe('image')
})
it('should create an instance of SVG.Rect', function() {
expect(draw.image(imageUrl, 100, 100) instanceof SVG.Image).toBe(true)
})
it('should be an instance of SVG.Shape', function() {
expect(draw.image(imageUrl, 100, 100) instanceof SVG.Shape).toBe(true)
})
it('should be an instance of SVG.Element', function() {
expect(draw.image(imageUrl, 100, 100) instanceof SVG.Element).toBe(true)
})
})
describe('text()', function() {
it('increases children by 1', function() {
var initial = draw.children().length
draw.text(loremIpsum)
expect(draw.children().length).toBe(initial + 1)
})
it('creates a text element', function() {
expect(draw.text(loremIpsum).type).toBe('text')
})
it('creates an instance of SVG.Rect', function() {
expect(draw.text(loremIpsum) instanceof SVG.Text).toBe(true)
})
it('is an instance of SVG.Shape', function() {
expect(draw.text(loremIpsum) instanceof SVG.Shape).toBe(true)
})
it('is an instance of SVG.Element', function() {
expect(draw.text(loremIpsum) instanceof SVG.Element).toBe(true)
})
})
describe('plain()', function() {
it('increases children by 1', function() {
var initial = draw.children().length
draw.plain(loremIpsum)
expect(draw.children().length).toBe(initial + 1)
})
it('creates a plain element', function() {
expect(draw.plain(loremIpsum).type).toBe('text')
})
it('creates an instance of SVG.Rect', function() {
expect(draw.plain(loremIpsum) instanceof SVG.Text).toBe(true)
})
it('is an instance of SVG.Shape', function() {
expect(draw.plain(loremIpsum) instanceof SVG.Shape).toBe(true)
})
it('is an instance of SVG.Element', function() {
expect(draw.plain(loremIpsum) instanceof SVG.Element).toBe(true)
})
})
describe('clear()', function() {
it('removes all children except the parser if present', function() {
draw.rect(100,100)
draw.clear()
expect(draw.children().length).toBe(parserInDoc)
})
it('creates a new defs node', function() {
var oldDefs = draw.defs()
draw.rect(100,100).maskWith(draw.circle(100, 100))
draw.clear()
expect(draw.defs()).not.toBe(oldDefs)
})
it('clears all children in the defs node', function() {
draw.rect(100,100).maskWith(draw.circle(100, 100))
draw.clear()
expect(draw.defs().children().length).toBe(0)
})
})
describe('each()', function() {
it('should iterate over all children', function() {
var children = []
draw.rect(100,100)
draw.ellipse(100, 100)
draw.polygon()
draw.each(function() {
children.push(this.type)
})
expect(children).toEqual((parserInDoc ? [parser[0].type] : []).concat(['rect', 'ellipse', 'polygon']))
})
it('should only include the its own children', function() {
var children = []
, group = draw.group()
draw.rect(100,200)
draw.circle(300)
group.rect(100,100)
group.ellipse(100, 100)
group.polygon()
group.each(function() {
children.push(this)
})
expect(children).toEqual(group.children())
})
it('should traverse recursively when set to deep', function() {
var children = []
, group = draw.group()
draw.rect(100,200)
draw.circle(300)
group.rect(100,100)
group.ellipse(100, 100)
group.polygon()
draw.each(function() {
children.push(this)
}, true)
expect(children.length).toEqual(draw.children().length + group.children().length + (parserInDoc ? parser[0].children().length : 0))
})
})
describe('get()', function() {
it('gets an element at a given index', function() {
draw.clear()
var rect = draw.rect(100,100)
var circle = draw.circle(100)
var line = draw.line(0,0,100,100)
expect(draw.get(0+parserInDoc)).toBe(rect)
expect(draw.get(1+parserInDoc)).toBe(circle)
expect(draw.get(2+parserInDoc)).toBe(line)
expect(draw.get(3+parserInDoc)).toBeNull()
})
})
describe('first()', function() {
it('gets the first child', function() {
draw.clear()
var rect = draw.rect(100,100)
var circle = draw.circle(100)
var line = draw.line(0,0,100,100)
expect(draw.first()).toBe(parserInDoc ? parser[0] : rect)
})
})
describe('last()', function() {
it('gets the last child', function() {
draw.clear()
var rect = draw.rect(100,100)
var circle = draw.circle(100)
var line = draw.line(0,0,100,100)
expect(draw.last()).toBe(line)
})
})
describe('has()', function() {
it('determines if a given element is a child of the parent', function() {
var rect = draw.rect(100,100)
var circle = draw.circle(100)
var group = draw.group()
var line = group.line(0,0,100,100)
expect(draw.has(rect)).toBe(true)
expect(draw.has(circle)).toBe(true)
expect(draw.has(group)).toBe(true)
expect(draw.has(line)).toBe(false)
expect(group.has(line)).toBe(true)
})
})
describe('index()', function() {
it('determines the index of given element', function() {
var rect = draw.rect(100,100)
var circle = draw.circle(100)
var group = draw.group()
var line = group.line(0,0,100,100)
expect(draw.index(rect)).toBe(0+parserInDoc)
expect(draw.index(circle)).toBe(1+parserInDoc)
expect(draw.index(group)).toBe(2+parserInDoc)
expect(draw.index(line)).toBe(-1)
expect(group.index(line)).toBe(0)
})
})
describe('parent()', function() {
it('returns the parent element instance', function() {
var rect = draw.rect(100,100)
expect(rect.parent()).toBe(rect.node.parentNode.instance)
})
})
describe('defs()', function() {
it('returns the defs from the svg', function() {
var g = draw.group()
expect(g.defs()).toBe(draw.doc().defs())
expect(g.defs() instanceof SVG.Defs).toBeTruthy()
})
})
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 | 2 | describe('Defs', function() {
var defs
beforeEach(function() {
defs = draw.defs()
})
it('creates an instance of SVG.Defs', function() {
expect(defs instanceof SVG.Defs).toBeTruthy()
})
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 2 | describe('SVG.easing', function() {
var easedValues = {
'-':0.5,
'<>':0.5,
'>':0.7071,
'<':0.2929,
}
;['-', '<>', '<', '>'].forEach(function(el) {
describe(el, function() {
it('is 0 at 0', function() {
expect(SVG.easing[el](0)).toBe(0)
})
it('is 1 at 1', function() {
expect(Math.round(SVG.easing[el](1)*1000)/1000).toBe(1) // we need to round cause for some reason at some point 1==0.999999999
})
it('is eased at 0.5', function() {
expect(SVG.easing[el](0.5)).toBeCloseTo(easedValues[el])
})
})
})
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 | 2 | describe('Element', function() {
beforeEach(function() {
draw.clear()
draw.attr('viewBox', null)
})
it('should create a circular reference on the node', function() {
var rect = draw.rect(100,100)
expect(rect.node.instance).toBe(rect)
})
describe('native()', function() {
it('returns the node reference', function() {
var rect = draw.rect(100,100)
expect(rect.native()).toBe(rect.node)
})
})
describe('attr()', function() {
var rect
beforeEach(function() {
rect = draw.rect(100,100)
})
afterEach(function() {
rect.remove()
draw.defs().select('pattern').each(function() { this.remove() })
})
it('sets one attribute when two arguments are given', function() {
rect.attr('fill', '#ff0066')
expect(rect.node.getAttribute('fill')).toBe('#ff0066')
})
it('sets various attributes when an object is given', function() {
rect.attr({ fill: '#00ff66', stroke: '#ff2233', 'stroke-width': 10 })
expect(rect.node.getAttribute('fill')).toBe('#00ff66')
expect(rect.node.getAttribute('stroke')).toBe('#ff2233')
expect(rect.node.getAttribute('stroke-width')).toBe('10')
})
it('gets the value of the string value given as first argument', function() {
rect.attr('fill', '#ff0066')
expect(rect.attr('fill')).toEqual('#ff0066')
})
it('gets an object with all attributes without any arguments', function() {
rect.attr({ fill: '#00ff66', stroke: '#ff2233' })
var attr = rect.attr()
expect(attr.fill).toBe('#00ff66')
expect(attr.stroke).toBe('#ff2233')
})
it('removes an attribute if the second argument is explicitly set to null', function() {
rect.attr('stroke-width', 10)
expect(rect.node.getAttribute('stroke-width')).toBe('10')
rect.attr('stroke-width', null)
expect(rect.node.getAttribute('stroke-width')).toBe(null)
})
it('correctly parses numeric values as a getter', function() {
rect.attr('stroke-width', 11)
expect(rect.node.getAttribute('stroke-width')).toBe('11')
expect(rect.attr('stroke-width')).toBe(11)
})
it('correctly parses negative numeric values as a getter', function() {
rect.attr('x', -120)
expect(rect.node.getAttribute('x')).toBe('-120')
expect(rect.attr('x')).toBe(-120)
})
it('falls back on default values if attribute is not present', function() {
expect(rect.attr('stroke-linejoin')).toBe('miter')
})
it('gets the "style" attribute as a string', function() {
rect.style('cursor', 'pointer')
expect(rect.node.style.cursor).toBe('pointer')
})
it('sets the style attribute correctly', function() {
rect.attr('style', 'cursor:move;')
expect(rect.node.style.cursor).toBe('move')
})
it('acts as a global getter when no arguments are given', function() {
rect.fill('#ff0066')
expect(rect.attr().fill).toBe('#ff0066')
})
it('correctly parses numeric values as a global getter', function() {
rect.stroke({ width: 20 })
expect(rect.attr()['stroke-width']).toBe(20)
})
it('correctly parses negative numeric values as a global getter', function() {
rect.x(-30)
expect(rect.attr().x).toBe(-30)
})
it('leaves unit values alone as a global getter', function() {
rect.attr('x', '69%')
expect(rect.attr().x).toBe('69%')
})
it('creates an image in defs when image path is specified for fill', function() {
rect.attr('fill', imageUrl)
expect(draw.defs().select('pattern').length()).toBe(1)
expect(draw.defs().select('pattern image').length()).toBe(1)
expect(draw.defs().select('pattern image').first().src).toBe(imageUrl)
})
it('creates pattern in defs when image object is specified for fill', function() {
rect.attr('fill', new SVG.Image().load(imageUrl))
expect(draw.defs().select('pattern').length()).toBe(1)
expect(draw.defs().select('pattern image').length()).toBe(1)
expect(draw.defs().select('pattern image').first().src).toBe(imageUrl)
})
it('correctly creates SVG.Array if array given', function() {
rect.attr('something', [2,3,4])
expect(rect.attr('something')).toBe('2 3 4')
})
it('redirects to the leading() method when setting leading', function() {
var text = draw.text(loremIpsum)
spyOn(text, 'leading')
text.attr('leading', 2)
expect(text.leading).toHaveBeenCalled()
text.remove()
})
})
describe('id()', function() {
var rect
beforeEach(function() {
rect = draw.rect(100,100)
})
it('gets the value if the id attribute without an argument', function() {
expect(rect.id()).toBe(rect.attr('id'))
})
it('sets the value of the id', function() {
rect.id('new_id')
expect(rect.attr('id')).toBe('new_id')
})
})
describe('style()', function() {
it('sets the style with key and value arguments', function() {
var rect = draw.rect(100,100).style('cursor', 'crosshair')
expect(window.stripped(rect.node.style.cssText)).toBe('cursor:crosshair')
})
it('sets multiple styles with an object as the first argument', function() {
var rect = draw.rect(100,100).style({ cursor: 'help', display: 'block' })
expect(window.stripped(rect.node.style.cssText)).toMatch(/cursor:help/)
expect(window.stripped(rect.node.style.cssText)).toMatch(/display:block/)
expect(window.stripped(rect.node.style.cssText).length).toBe(('display:block;cursor:help').length)
})
it('sets multiple styles with a css string as the first argument', function() {
var rect = draw.rect(100,100).style('cursor: help; display: block;')
expect(window.stripped(rect.node.style.cssText)).toMatch(/cursor:help/)
expect(window.stripped(rect.node.style.cssText)).toMatch(/display:block/)
expect(window.stripped(rect.node.style.cssText).length).toBe(('display:block;cursor:help').length)
})
it('gets a style with a string key as the fists argument', function() {
var rect = draw.rect(100,100).style({ cursor: 'progress', display: 'block' })
expect(rect.style('cursor')).toBe('progress')
})
it('gets the full css string with no argument', function() {
var rect = draw.rect(100,100).style({ cursor: 's-resize', display: 'none' })
expect(window.stripped(rect.style())).toMatch(/display:none/)
expect(window.stripped(rect.style())).toMatch(/cursor:s-resize/)
expect(window.stripped(rect.style()).length).toBe(('cursor:s-resize;display:none').length)
})
it('removes a style if the value is an empty string', function() {
var rect = draw.rect(100,100).style({ cursor: 'n-resize', display: '' })
expect(window.stripped(rect.style())).toBe('cursor:n-resize')
})
it('removes a style if the value explicitly set to null', function() {
var rect = draw.rect(100,100).style('cursor', 'w-resize')
expect(window.stripped(rect.style())).toBe('cursor:w-resize')
rect.style('cursor', null)
expect(rect.style()).toBe('')
})
})
describe('transform()', function() {
var rect, ctm
beforeEach(function() {
rect = draw.rect(100,100)
})
it('gets the current transformations', function() {
expect(rect.transform()).toEqual(new SVG.Matrix(rect).extract())
})
it('sets the translation of and element', function() {
rect.transform({ x: 10, y: 11 })
expect(window.matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([1,0,0,1,10,11])
})
it('performs an absolute translation', function() {
rect.transform({ x: 10, y: 11 }).transform({ x: 20, y: 21 })
expect(window.matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([1,0,0,1,20,21])
})
it('performs a relative translation when relative is set to true', function() {
rect.transform({ x: 10, y: 11 }).transform({ x: 20, y: 21, relative: true })
expect(window.matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([1,0,0,1,30,32])
})
it('performs a relative translation with relative flag', function() {
rect.transform({ x: 10, y: 11 }).transform({ x: 20, y: 21 }, true)
expect(window.matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([1,0,0,1,30,32])
})
it('sets the scaleX and scaleY of an element', function() {
rect.transform({ scaleX: 0.5, scaleY: 2 })
expect(window.matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([0.5,0,0,2,25,-50])
})
it('performs a uniform scale with scale given', function() {
rect.transform({ scale: 3 })
expect(window.matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([3,0,0,3,-100,-100])
})
it('also works with only skaleX', function() {
rect.transform({ scaleX: 3 })
expect(window.matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([3,0,0,1,-100,0])
})
it('also works with only skaleY', function() {
rect.transform({ scaleY: 3 })
expect(window.matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([1,0,0,3,0,-100])
})
it('performs an absolute scale by default', function() {
rect.transform({ scale: 3 }).transform({ scale: 0.5 })
expect(window.matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([0.5,0,0,0.5,25,25])
})
it('performs a relative scale with a relative flag', function() {
rect.transform({ scaleX: 0.5, scaleY: 2 }).transform({ scaleX: 3, scaleY: 4 }, true)
expect(window.matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([1.5,0,0,8,-25,-350])
})
it('sets the skewX of an element with center on the element', function() {
ctm = rect.transform({ skewX: 10 }).ctm()
expect(ctm.a).toBe(1)
expect(ctm.b).toBe(0)
expect(ctm.c).toBeCloseTo(0.17632698070846498)
expect(ctm.d).toBe(1)
expect(ctm.e).toBeCloseTo(-8.81634903542325)
expect(ctm.f).toBe(0)
})
it('sets the skewX of an element with given center', function() {
ctm = rect.transform({ skewX: 10, cx: 0, cy: 0 }).ctm()
expect(ctm.a).toBe(1)
expect(ctm.b).toBe(0)
expect(ctm.c).toBeCloseTo(0.17632698070846498)
expect(ctm.d).toBe(1)
expect(ctm.e).toBe(0)
expect(ctm.f).toBe(0)
})
it('sets the skewY of an element', function() {
ctm = rect.transform({ skewY: -10, cx: 0, cy: 0 }).ctm()
expect(ctm.a).toBe(1)
expect(ctm.b).toBeCloseTo(-0.17632698070846498)
expect(ctm.c).toBe(0)
expect(ctm.d).toBe(1)
expect(ctm.e).toBe(0)
expect(ctm.f).toBe(0)
})
it('sets the skewX and skewY of an element', function() {
ctm = rect.transform({ skewX: 10, skewY: -10, cx: 0, cy: 0 }).ctm()
expect(ctm.a).toBe(1)
expect(ctm.b).toBeCloseTo(-0.17632698070846498)
expect(ctm.c).toBeCloseTo(0.17632698070846498)
expect(ctm.d).toBe(1)
expect(ctm.e).toBe(0)
expect(ctm.f).toBe(0)
})
it('performs a uniform skew with skew given', function() {
ctm = rect.transform({ skew: 5, cx: 0, cy: 0 }).ctm()
expect(ctm.a).toBe(1)
expect(ctm.b).toBeCloseTo(0.08748866352592401)
expect(ctm.c).toBeCloseTo(0.08748866352592401)
expect(ctm.d).toBe(1)
expect(ctm.e).toBe(0)
expect(ctm.f).toBe(0)
})
it('rotates the element around its centre if no rotation point is given', function() {
ctm = rect.center(100, 100).transform({ rotation: 45 }).ctm()
expect(ctm.a).toBeCloseTo(0.7071068286895752)
expect(ctm.b).toBeCloseTo(0.7071068286895752)
expect(ctm.c).toBeCloseTo(-0.7071068286895752)
expect(ctm.d).toBeCloseTo(0.7071068286895752)
expect(ctm.e).toBeCloseTo(100)
expect(ctm.f).toBeCloseTo(-41.421356201171875)
expect(rect.transform('rotation')).toBe(45)
})
it('rotates the element around the given rotation point', function() {
ctm = rect.transform({ rotation: 55, cx: 80, cy:2 }).ctm()
expect(ctm.a).toBeCloseTo(0.5735765099525452)
expect(ctm.b).toBeCloseTo(0.8191521167755127)
expect(ctm.c).toBeCloseTo(-0.8191521167755127)
expect(ctm.d).toBeCloseTo(0.5735765099525452)
expect(ctm.e).toBeCloseTo(35.75218963623047)
expect(ctm.f).toBeCloseTo(-64.67931365966797)
})
it('transforms element using a matrix', function() {
rect.transform({ a: 0.5, c: 0.5 })
expect(window.matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([0.5,0,0.5,1,0,0])
})
it('transforms relative using a matrix', function() {
rect.transform({ a: 0.5, c: 0.5 }).transform(new SVG.Matrix({ e: 20, f: 20 }), true)
expect(window.matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([0.5,0,0.5,1,20,20])
})
it('flips the element on x axis', function() {
rect.transform({ flip: 'x' })
expect(window.matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([-1,0,0,1,100,0])
})
it('flips the element on x axis with offset', function() {
rect.transform({ flip: 'x', offset: 20 })
expect(window.matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([-1,0,0,1,40,0])
})
it('flips the element on y axis with offset', function() {
rect.transform({ flip: 'y', offset: 20 })
expect(window.matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([1,0,0,-1,0,40])
})
it('flips the element on both axis with offset', function() {
rect.transform({ flip: 'both', offset: 20 })
expect(window.matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([-1,0,0,-1,40,40])
})
it('flips the element on both axis', function() {
rect.transform({ flip: 'both' })
expect(window.matrixStringToArray(rect.node.getAttribute('transform'))).toEqual([-1,0,0,-1,100,100])
})
})
describe('untransform()', function() {
var circle
beforeEach(function() {
circle = draw.circle(100).translate(50, 100)
})
it('removes the transform attribute', function() {
expect(window.matrixStringToArray(circle.node.getAttribute('transform'))).toEqual([1,0,0,1,50,100])
circle.untransform()
expect(circle.node.getAttribute('transform')).toBeNull()
})
it('resets the current transform matix', function() {
expect(circle.ctm()).toEqual(new SVG.Matrix(1,0,0,1,50,100))
circle.untransform()
expect(circle.ctm()).toEqual(new SVG.Matrix)
})
})
describe('matrixify', function() {
var rect
beforeEach(function() {
rect = draw.rect(100, 100)
})
it('allow individual transform definitions to be separated by whitespace', function(){
// One space
rect.attr('transform', 'translate(20) translate(20)')
expect(rect.matrixify().toString()).toBe('matrix(1,0,0,1,40,0)')
// More than one space
rect.attr('transform', 'translate(20) translate(-60)')
expect(rect.matrixify().toString()).toBe('matrix(1,0,0,1,-40,0)')
})
it('allow individual transform definitions to be separated by a comma', function(){
rect.attr('transform', 'translate(20,16),translate(20)')
expect(rect.matrixify().toString()).toBe('matrix(1,0,0,1,40,16)')
})
it('allow individual transform definitions to be separated by whitespace and a comma', function(){
// Spaces before the comma
rect.attr('transform', 'translate(20,16) ,translate(20)')
expect(rect.matrixify().toString()).toBe('matrix(1,0,0,1,40,16)')
// Spaces after the comma
rect.attr('transform', 'translate(12), translate(10,14)')
expect(rect.matrixify().toString()).toBe('matrix(1,0,0,1,22,14)')
// Spaces before and after the comma
rect.attr('transform', 'translate(24,14) , translate(36,6)')
expect(rect.matrixify().toString()).toBe('matrix(1,0,0,1,60,20)')
})
})
describe('toParent()', function() {
var nested, g1, g2, rect1
beforeEach(function() {
nested = draw.nested()
g1 = nested.group().translate(20, 20)
g2 = g1.group().translate(100, 100)
rect1 = g2.rect(100,100).scale(2)
rect2 = nested.rect(100,100).scale(0.5)
})
afterEach(function() {
draw.clear()
})
it('returns itself when given parent and it is the same', function() {
expect(g2.toParent(g2)).toBe(g2)
})
it('moves the element to other parent while maintaining the same visal representation', function() {
expect(rect1.toParent(nested).transform()).toEqual(jasmine.objectContaining({
a:2, b:0, c:0, d:2, e:70, f:70
}))
expect(rect1.parent()).toEqual(nested)
expect(rect2.toParent(g2).transform()).toEqual(jasmine.objectContaining({
a:0.5, b:0, c:0, d:0.5, e:-95, f:-95
}))
expect(rect2.parent()).toEqual(g2)
})
})
describe('toDoc()', function() {
var nested, g1, g2, rect
beforeEach(function() {
rect = draw.rect(100,100)
spyOn(rect, 'toParent')
})
afterEach(function() {
draw.clear()
})
it('redirects to toParent(doc)', function() {
rect.toDoc()
expect(rect.toParent).toHaveBeenCalledWith(rect.doc())
})
})
describe('ungroup()', function() {
var nested, g1, g2, rect1
beforeEach(function() {
draw.defs()
nested = draw.nested()
g1 = nested.group().translate(20, 20)
g2 = g1.group().translate(100, 100)
rect1 = g2.rect(100,100).scale(2)
rect2 = g1.rect(100,100).scale(0.5)
})
afterEach(function() {
draw.clear()
})
it('returns itself when depths is 0 or this is SVG.Defs', function() {
expect(draw.defs().ungroup()).toBe(draw.defs())
expect(g1.ungroup(null, 0)).toBe(g1)
})
it('breaks up all container and move the elements to the parent', function() {
g1.ungroup()
expect(rect1.parent()).toBe(nested)
expect(rect2.parent()).toBe(nested)
expect(g1.node.parentNode).toBeFalsy()
expect(g2.node.parentNode).toBeFalsy()
expect(rect1.transform()).toEqual(jasmine.objectContaining({
a:2, b:0, c:0, d:2, e:70, f:70
}))
expect(rect2.transform()).toEqual(jasmine.objectContaining({
a:0.5, b:0, c:0, d:0.5, e:45, f:45
}))
})
it('ungroups everything to the doc root when called on SVG.Doc / does not ungroup defs/parser', function() {
draw.ungroup()
expect(rect1.parent()).toBe(draw)
expect(rect2.parent()).toBe(draw)
expect(g1.node.parentNode).toBeFalsy()
expect(g1.node.parentNode).toBeFalsy()
expect(nested.node.parentNode).toBeFalsy()
expect(rect1.transform()).toEqual(jasmine.objectContaining({
a:2, b:0, c:0, d:2, e:70, f:70
}))
expect(rect2.transform()).toEqual(jasmine.objectContaining({
a:0.5, b:0, c:0, d:0.5, e:45, f:45
}))
expect(draw.children().length).toBe(3+parserInDoc) // 2 * rect + defs
})
})
describe('flatten()', function() {
it('redirects the call to ungroup()', function() {
spyOn(draw, 'ungroup')
draw.flatten()
expect(draw.ungroup).toHaveBeenCalled()
})
})
describe('ctm()', function() {
var rect
beforeEach(function() {
rect = draw.rect(100, 100)
})
it('gets the current transform matrix of the element', function() {
rect.translate(10, 20)
expect(rect.ctm().toString()).toBe('matrix(1,0,0,1,10,20)')
})
it('returns an instance of SVG.Matrix', function() {
expect(rect.ctm() instanceof SVG.Matrix).toBeTruthy()
})
})
describe('data()', function() {
it('sets a data attribute and convert value to json', function() {
var rect = draw.rect(100,100).data('test', 'value')
expect(rect.node.getAttribute('data-test')).toBe('value')
})
it('sets a data attribute and not convert value to json if flagged raw', function() {
var rect = draw.rect(100,100).data('test', 'value', true)
expect(rect.node.getAttribute('data-test')).toBe('value')
})
it('sets multiple data attributes and convert values to json when an object is passed', function() {
var rect = draw.rect(100,100).data({
forbidden: 'fruit'
, multiple: {
values: 'in'
, an: 'object'
}
})
expect(rect.node.getAttribute('data-forbidden')).toBe('fruit')
expect(rect.node.getAttribute('data-multiple')).toEqual('{"values":"in","an":"object"}')
})
it('gets data value if only one argument is passed', function() {
var rect = draw.rect(100,100).data('test', 101)
expect(rect.data('test')).toBe(101)
})
it('gets the raw value when value is no valid json', function() {
var rect = draw.rect(100,100).data('test', '{["sd":12}]', true)
expect(rect.data('test')).toBe('{["sd":12}]')
})
it('removes data when null given', function() {
var rect = draw.rect(100,100).data('test', '{"sd":12}', true)
expect(rect.data('test', null).attr('data-test')).toBeFalsy()
})
it('maintains data type for a number', function() {
var rect = draw.rect(100,100).data('test', 101)
expect(typeof rect.data('test')).toBe('number')
})
it('maintains data type for an object', function() {
var rect = draw.rect(100,100).data('test', { string: 'value', array: [1,2,3] })
expect(typeof rect.data('test')).toBe('object')
expect(Array.isArray(rect.data('test').array)).toBe(true)
})
})
describe('remove()', function() {
it('removes an element and return it', function() {
var rect = draw.rect(100,100)
expect(rect.remove()).toBe(rect)
})
it('removes an element from its parent', function() {
var rect = draw.rect(100,100)
rect.remove()
expect(draw.has(rect)).toBe(false)
})
})
describe('addTo()', function() {
it('adds an element to a given parent and returns itself', function() {
var rect = draw.rect(100,100)
, group = draw.group()
expect(rect.addTo(group)).toBe(rect)
expect(rect.parent()).toBe(group)
})
})
describe('putIn()', function() {
it('adds an element to a given parent and returns parent', function() {
var rect = draw.rect(100,100)
, group = draw.group()
expect(rect.putIn(group)).toBe(group)
expect(rect.parent()).toBe(group)
})
})
describe('rbox()', function() {
it('returns an instance of SVG.RBox', function() {
var rect = draw.rect(100,100)
expect(rect.rbox() instanceof SVG.RBox).toBe(true)
})
it('returns the correct rectangular box', function() {
// stroke has to be set in order to get the correct result when calling getBoundingClientRect in IE11
var rect = draw.size(200, 150).viewbox(0, 0, 200, 150).rect(105, 210).move(2, 12).stroke({width:0})
var box = rect.rbox(draw)
expect(box.x).toBeCloseTo(2)
expect(box.y).toBeCloseTo(12)
expect(box.cx).toBeCloseTo(54.5)
expect(box.cy).toBeCloseTo(117)
expect(box.width).toBeCloseTo(105)
expect(box.height).toBeCloseTo(210)
})
})
describe('doc()', function() {
it('returns the parent document', function() {
var rect = draw.rect(100,100)
expect(rect.doc()).toBe(draw)
})
})
describe('parent()', function() {
it('contains the parent svg', function() {
var rect = draw.rect(100,100)
expect(rect.parent()).toBe(draw)
})
it('contains the parent group when in a group', function() {
var group = draw.group()
, rect = group.rect(100,100)
expect(rect.parent()).toBe(group)
})
it('contains the parent which matches type', function() {
var group = draw.group()
, rect = group.rect(100,100)
expect(rect.parent(SVG.Doc)).toBe(draw)
})
it('contains the parent which matches selector', function() {
var group1 = draw.group().addClass('test')
, group2 = group1.group()
, rect = group2.rect(100,100)
expect(rect.parent('.test')).toBe(group1)
})
})
describe('parents()', function() {
it('returns array of parent up to but not including the dom element filtered by type', function() {
var group1 = draw.group().addClass('test')
, group2 = group1.group()
, rect = group2.rect(100,100)
expect(rect.parents('.test')[0]).toBe(group1)
expect(rect.parents(SVG.G)[0]).toBe(group2)
expect(rect.parents(SVG.G)[1]).toBe(group1)
expect(rect.parents().length).toBe(3)
})
})
describe('clone()', function() {
var rect, group, circle
beforeEach(function() {
rect = draw.rect(100,100).center(321,567).fill('#f06')
group = draw.group().add(rect)
circle = group.circle(100)
})
it('makes an exact copy of the element', function() {
clone = rect.clone()
expect(clone.attr('id', null).attr()).toEqual(rect.attr('id', null).attr())
})
it('assigns a new id to the cloned element', function() {
clone = rect.clone()
expect(clone.attr('id')).not.toBe(rect.attr('id'))
})
it('copies all child nodes as well', function() {
clone = group.clone()
expect(clone.children().length).toBe(group.children().length)
})
it('assigns a new id to cloned child elements', function() {
clone = group.clone()
expect(clone.attr('id')).not.toEqual(group.attr('id'))
expect(clone.get(0).attr('id')).not.toBe(group.get(0).attr('id'))
expect(clone.get(1).attr('id')).not.toBe(group.get(1).attr('id'))
})
it('inserts the clone after the cloned element', function() {
clone = rect.clone()
expect(rect.next()).toBe(clone)
})
it('inserts the clone in the specified parent', function() {
var g = draw.group()
clone = rect.clone(g)
expect(g.get(0)).toBe(clone)
})
it('deep copies over dom data', function() {
group.dom = {'foo':'bar'}
rect.dom = {'foo':'baz'}
clone = group.clone()
expect(clone.dom.foo).toBe('bar')
expect(clone.get(0).dom.foo).toBe('baz')
})
})
describe('toString()', function() {
it('returns the element id', function() {
var rect = draw.rect(100,100).center(321,567).fill('#f06')
expect(rect + '').toBe(rect.attr('id'))
})
})
describe('replace()', function() {
it('replaces the original element by another given element', function() {
var rect = draw.rect(100,100).center(321,567).fill('#f06')
var circle = draw.circle(200)
var rectIndex = draw.children().indexOf(rect)
rect.replace(circle)
expect(rectIndex).toBe(draw.children().indexOf(circle))
})
it('removes the original element', function() {
var rect = draw.rect(100,100).center(321,567).fill('#f06')
rect.replace(draw.circle(200))
expect(draw.has(rect)).toBe(false)
})
it('returns the new element', function() {
var circle = draw.circle(200)
var element = draw.rect(100,100).center(321,567).fill('#f06').replace(circle)
expect(element).toBe(circle)
})
})
describe('classes()', function() {
it('returns an array of classes on the node', function() {
var element = draw.rect(100,100)
element.node.setAttribute('class', 'one two')
expect(element.classes()).toEqual(['one', 'two'])
})
})
describe('hasClass()', function() {
it('returns true if the node has the class', function() {
var element = draw.rect(100,100)
element.node.setAttribute('class', 'one')
expect(element.hasClass('one')).toBeTruthy()
})
it('returns false if the node does not have the class', function() {
var element = draw.rect(100,100)
element.node.setAttribute('class', 'one')
expect(element.hasClass('two')).toBeFalsy()
})
})
describe('addClass()', function() {
it('adds the class to the node', function() {
var element = draw.rect(100,100)
element.addClass('one')
expect(element.hasClass('one')).toBeTruthy()
})
it('does not add duplicate classes', function() {
var element = draw.rect(100,100)
element.addClass('one')
element.addClass('one')
expect(element.node.getAttribute('class')).toEqual('one')
})
it('returns the svg instance', function() {
var element = draw.rect(100,100)
expect(element.addClass('one')).toEqual(element)
})
})
describe('removeClass()', function() {
it('removes the class from the node when the class exists', function() {
var element = draw.rect(100,100)
element.addClass('one')
element.removeClass('one')
expect(element.hasClass('one')).toBeFalsy()
})
it('does nothing when the class does not exist', function() {
var element = draw.rect(100,100)
element.removeClass('one')
expect(element.hasClass('one')).toBeFalsy()
})
it('returns the element', function() {
var element = draw.rect(100,100)
expect(element.removeClass('one')).toEqual(element)
})
})
describe('toggleClass()', function() {
it('adds the class when it does not already exist', function(){
var element = draw.rect(100,100)
element.toggleClass('one')
expect(element.hasClass('one')).toBeTruthy()
})
it('removes the class when it already exists', function(){
var element = draw.rect(100,100)
element.addClass('one')
element.toggleClass('one')
expect(element.hasClass('one')).toBeFalsy()
})
it('returns the svg instance', function() {
var element = draw.rect(100,100)
expect(element.toggleClass('one')).toEqual(element)
})
})
describe('reference()', function() {
it('gets a referenced element from a given attribute', function() {
var rect = draw.defs().rect(100, 100)
, use = draw.use(rect)
, mark = draw.marker(10, 10)
, path = draw.path(svgPath).marker('end', mark)
expect(use.reference('href')).toBe(rect)
expect(path.reference('marker-end')).toBe(mark)
})
})
describe('svg()', function() {
describe('without an argument', function() {
it('returns full raw svg when called on the main svg doc', function() {
draw.size(100,100).rect(100,100).id(null)
draw.circle(100).fill('#f06').id(null)
var toBeTested = draw.svg()
// Test for different browsers namely Firefox and Chrome
expect(
// IE
toBeTested === '<svg xmlns:svgjs="http://svgjs.com/svgjs" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" xmlns="http://www.w3.org/2000/svg" height="100" width="100" id="' + draw.id() + '"><rect height="100" width="100"></rect><circle fill="#ff0066" cy="50" cx="50" r="50"></circle></svg>'
// Firefox
|| toBeTested === '<svg id="' + draw.id() + '" width="100" height="100" xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:svgjs="http://svgjs.com/svgjs"><rect width="100" height="100"></rect><circle r="50" cx="50" cy="50" fill="#ff0066"></circle></svg>'
// svgdom
|| toBeTested === '<svg id="' + draw.id() + '" xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:svgjs="http://svgjs.com/svgjs" width="100" height="100"><svg id="SvgjsSvg1002" width="2" height="0" style="overflow: hidden; top: -100%; left: -100%; position: absolute; opacity: 0"><polyline id="SvgjsPolyline1003" points="10,10 20,10 30,10"></polyline><path id="SvgjsPath1004" d="M80 80A45 45 0 0 0 125 125L125 80Z "></path></svg><rect width="100" height="100"></rect><circle r="50" cx="50" cy="50" fill="#ff0066"></circle></svg>'
).toBeTruthy()
})
it('returns partial raw svg when called on a sub group', function() {
var group = draw.group().id(null)
group.rect(100,100).id(null)
group.circle(100).fill('#f06').id(null)
var toBeTested = group.svg()
expect(
toBeTested === '<g><rect width="100" height="100"></rect><circle r="50" cx="50" cy="50" fill="#ff0066"></circle></g>'
|| toBeTested === '<g><rect height="100" width="100"></rect><circle fill="#ff0066" cy="50" cx="50" r="50"></circle></g>'
|| toBeTested === '<g xmlns="http://www.w3.org/2000/svg"><rect width="100" height="100"></rect><circle r="50" cx="50" cy="50" fill="#ff0066"></circle></g>'
).toBeTruthy()
})
it('returns a single element when called on an element', function() {
var group = draw.group().id(null)
group.rect(100,100).id(null)
var circle = group.circle(100).fill('#f06').id(null)
var toBeTested = circle.svg()
expect(
toBeTested === '<circle r="50" cx="50" cy="50" fill="#ff0066"></circle>'
|| toBeTested === '<circle fill="#ff0066" cy="50" cx="50" r="50"></circle>'
|| toBeTested === '<circle xmlns="http://www.w3.org/2000/svg" r="50" cx="50" cy="50" fill="#ff0066"></circle>'
).toBeTruthy()
})
})
describe('with raw svg given', function() {
it('imports a full svg document', function() {
draw.svg('<svg id="SvgjsSvg1000" xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="100" height="100" viewBox="0 0 50 50"><rect id="SvgjsRect1183" width="100" height="100"></rect><circle id="SvgjsCircle1184" r="50" cx="25" cy="25" fill="#ff0066"></circle></svg>')
expect(draw.get(0+parserInDoc).type).toBe('svg')
expect(draw.get(0+parserInDoc).children().length).toBe(2)
expect(draw.get(0+parserInDoc).get(0).type).toBe('rect')
expect(draw.get(0+parserInDoc).get(1).type).toBe('circle')
expect(draw.get(0+parserInDoc).get(1).attr('fill')).toBe('#ff0066')
})
it('imports partial svg content', function() {
draw.svg('<g id="SvgjsG1185"><rect id="SvgjsRect1186" width="100" height="100"></rect><circle id="SvgjsCircle1187" r="50" cx="25" cy="25" fill="#ff0066"></circle></g>')
expect(draw.get(0+parserInDoc).type).toBe('g')
expect(draw.get(0+parserInDoc).get(0).type).toBe('rect')
expect(draw.get(0+parserInDoc).get(1).type).toBe('circle')
expect(draw.get(0+parserInDoc).get(1).attr('fill')).toBe('#ff0066')
})
it('does not import on single elements, even with an argument it acts as a getter', function() {
var rect = draw.rect(100,100).id(null)
, result = rect.svg('<circle r="300"></rect>')
expect(
result === '<rect width="100" height="100"></rect>'
|| result === '<rect height="100" width="100"></rect>'
|| result === '<rect xmlns="http://www.w3.org/2000/svg" width="100" height="100"></rect>'
).toBeTruthy()
})
})
})
describe('writeDataToDom()', function() {
it('set all properties in el.dom to the svgjs:data attribute', function(){
var rect = draw.rect(100,100)
rect.dom.foo = 'bar'
rect.dom.number = new SVG.Number('3px')
rect.writeDataToDom()
expect(rect.attr('svgjs:data')).toBe('{"foo":"bar","number":"3px"}')
})
it('recursively dumps the data', function() {
var g = draw.group()
rect = g.rect(100,100)
g.dom.foo = 'bar'
rect.dom.number = new SVG.Number('3px')
g.writeDataToDom()
expect(g.attr('svgjs:data')).toBe('{"foo":"bar"}')
expect(rect.attr('svgjs:data')).toBe('{"number":"3px"}')
})
it('uses lines() instead of each() when dealing with text', function() {
var text = draw.text('Hello\nWorld')
text.writeDataToDom()
expect(text.attr('svgjs:data')).toBe('{"leading":"1.3"}')
expect(text.lines().first().attr('svgjs:data')).toBe('{"newLined":true}')
})
})
describe('setData()', function() {
it('read all data from the svgjs:data attribute and assign it to el.dom', function(){
var rect = draw.rect(100,100)
rect.attr('svgjs:data', '{"foo":"bar","number":"3px"}')
rect.setData(JSON.parse(rect.attr('svgjs:data')))
expect(rect.dom.foo).toBe('bar')
expect(rect.dom.number).toBe('3px')
})
})
describe('point()', function() {
it('creates a point from screen coordinates transformed in the elements space', function(){
var rect = draw.rect(100,100)
var m = draw.node.getScreenCTM()
// alert([m.a, m.a, m.c, m.d, m.e, m.f].join(', '))
var translation = {x: m.e, y: m.f}
var pos = {x: 2, y:5}
expect(rect.point(pos.x, pos.y).x).toBeCloseTo(pos.x - translation.x)
expect(rect.point(pos.x, pos.y).y).toBeCloseTo(pos.y - translation.y)
})
})
describe('inside()', function() {
it('checks whether the given point inside the bounding box of the element', function() {
var rect = draw.rect(100,100)
expect(rect.inside(50,50)).toBeTruthy()
expect(rect.inside(150,150)).toBeFalsy()
})
})
describe('show()', function() {
it('sets display property to ""', function() {
var rect = draw.rect(100,100).show()
expect(rect.style('display')).toBe('')
})
})
describe('hide()', function() {
it('sets display property to none', function() {
var rect = draw.rect(100,100).hide()
expect(rect.style('display')).toBe('none')
})
})
describe('visible()', function() {
it('checks if element is hidden or not', function() {
var rect = draw.rect(100,100).hide()
expect(rect.visible()).toBeFalsy()
rect.show()
expect(rect.visible()).toBeTruthy()
})
})
describe('is()', function() {
it('checks if element is instance of a certain kind', function() {
var rect = draw.rect(100,100)
expect(rect.is(SVG.Rect)).toBeTruthy()
expect(rect.is(SVG.Element)).toBeTruthy()
expect(rect.is(SVG.Parent)).toBeFalsy()
})
})
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 | 2 | describe('Ellipse', function() {
var ellipse
beforeEach(function() {
ellipse = draw.ellipse(240,90)
})
afterEach(function() {
draw.clear()
})
describe('x()', function() {
it('returns the value of x without an argument', function() {
expect(ellipse.x()).toBe(0)
})
it('sets the value of x with the first argument', function() {
ellipse.x(123)
var box = ellipse.bbox()
expect(box.x).toBeCloseTo(123)
})
})
describe('y()', function() {
it('returns the value of y without an argument', function() {
expect(ellipse.y()).toBe(0)
})
it('sets the value of cy with the first argument', function() {
ellipse.y(345)
var box = ellipse.bbox()
expect(box.y).toBe(345)
})
})
describe('cx()', function() {
it('returns the value of cx without an argument', function() {
expect(ellipse.cx()).toBe(120)
})
it('sets the value of cx with the first argument', function() {
ellipse.cx(123)
var box = ellipse.bbox()
expect(box.cx).toBe(123)
})
})
describe('cy()', function() {
it('returns the value of cy without an argument', function() {
expect(ellipse.cy()).toBe(45)
})
it('sets the value of cy with the first argument', function() {
ellipse.cy(345)
var box = ellipse.bbox()
expect(box.cy).toBe(345)
})
})
describe('radius()', function() {
it('sets the rx and ry', function() {
ellipse.radius(10, 20)
expect(ellipse.node.getAttribute('rx')).toBe('10')
expect(ellipse.node.getAttribute('ry')).toBe('20')
})
it('sets the rx and ry if only rx given', function() {
ellipse.radius(30)
expect(ellipse.node.getAttribute('rx')).toBe('30')
expect(ellipse.node.getAttribute('ry')).toBe('30')
})
it('sets the rx and ry value correctly when given 0', function() {
ellipse.radius(11, 0)
expect(ellipse.node.getAttribute('rx')).toBe('11')
expect(ellipse.node.getAttribute('ry')).toBe('0')
})
})
describe('move()', function() {
it('sets the x and y position', function() {
ellipse.move(123, 456)
var box = ellipse.bbox()
expect(box.x).toBeCloseTo(123)
expect(box.y).toBeCloseTo(456)
})
})
describe('dx()', function() {
it('moves the x positon of the element relative to the current position', function() {
ellipse.move(50, 60)
ellipse.dx(100)
expect(ellipse.node.getAttribute('cx')).toBe('270')
})
})
describe('dy()', function() {
it('moves the y positon of the element relative to the current position', function() {
ellipse.move(50, 60)
ellipse.dy(120)
expect(ellipse.node.getAttribute('cy')).toBe('225')
})
})
describe('dmove()', function() {
it('moves the x and y positon of the element relative to the current position', function() {
ellipse.move(50,60)
ellipse.dmove(80, 25)
expect(ellipse.node.getAttribute('cx')).toBe('250')
expect(ellipse.node.getAttribute('cy')).toBe('130')
})
})
describe('center()', function() {
it('sets the cx and cy position', function() {
ellipse.center(321,567)
var box = ellipse.bbox()
expect(box.cx).toBe(321)
expect(box.cy).toBe(567)
})
})
describe('width()', function() {
it('sets the width of the element', function() {
ellipse.width(82)
expect(ellipse.node.getAttribute('rx')).toBe('41')
})
it('gets the width of the element if the argument is null', function() {
expect((ellipse.width() / 2).toString()).toBe(ellipse.node.getAttribute('rx'))
})
})
describe('height()', function() {
it('sets the height of the element', function() {
ellipse.height(1236)
expect(ellipse.node.getAttribute('ry')).toBe('618')
})
it('gets the height of the element if the argument is null', function() {
expect((ellipse.height() / 2).toString()).toBe(ellipse.node.getAttribute('ry'))
})
})
describe('size()', function() {
it('defines the rx and ry of the element', function() {
ellipse.size(987,654)
expect(ellipse.node.getAttribute('rx')).toBe((987 / 2).toString())
expect(ellipse.node.getAttribute('ry')).toBe((654 / 2).toString())
})
it('defines the width and height proportionally with only the width value given', function() {
var box = ellipse.bbox()
ellipse.size(500)
expect(ellipse.width()).toBe(500)
expect(ellipse.width() / ellipse.height()).toBe(box.width / box.height)
})
it('defines the width and height proportionally with only the height value given', function() {
var box = ellipse.bbox()
ellipse.size(null, 525)
expect(ellipse.height()).toBe(525)
expect(ellipse.width() / ellipse.height()).toBe(box.width / box.height)
})
})
describe('scale()', function() {
it('should scale the element universally with one argument', function() {
var box = ellipse.scale(2).rbox()
expect(box.width).toBe(ellipse.attr('rx') * 2 * 2)
expect(box.height).toBe(ellipse.attr('ry') * 2 * 2)
})
it('should scale the element over individual x and y axes with two arguments', function() {
var box = ellipse.scale(2, 3.5).rbox()
expect(box.width).toBe(ellipse.attr('rx') * 2 * 2)
expect(box.height).toBe(ellipse.attr('ry') * 2 * 3.5)
})
})
describe('translate()', function() {
it('sets the translation of an element', function() {
ellipse.transform({ x: 12, y: 12 })
expect(ellipse.node.getAttribute('transform')).toBe('matrix(1,0,0,1,12,12)')
})
})
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 | 2 | describe('Event', function() {
var rect, context
, toast = null
, fruitsInDetail = null,
action = function(e) {
toast = 'ready'
context = this
fruitsInDetail = e.detail || null
}
beforeEach(function() {
rect = draw.rect(100, 100)
spyOn(SVG,'on').and.callThrough()
})
afterEach(function() {
toast = context = null
})
if (!this.isTouchDevice) {
describe('click()', function() {
it('attaches an onclick event to the node of the element', function() {
rect.click(action)
expect(SVG.on).toHaveBeenCalledWith(rect.node, 'click', action)
})
it('fires the event on click', function() {
rect.click(action).fire('click')
expect(toast).toBe('ready')
})
it('applies the element as context', function() {
rect.click(action).fire('click')
expect(context).toBe(rect)
})
it('returns the called element', function() {
expect(rect.click(action)).toBe(rect)
})
})
describe('dblclick()', function() {
it('attaches an ondblclick event to the node of the element', function() {
rect.dblclick(action)
expect(SVG.on).toHaveBeenCalledWith(rect.node, 'dblclick', action)
})
it('fires the event on dblclick', function() {
rect.dblclick(action).fire('dblclick')
expect(toast).toBe('ready')
})
it('applies the element as context', function() {
rect.dblclick(action).fire('dblclick')
expect(context).toBe(rect)
})
it('returns the called element', function() {
expect(rect.dblclick(action)).toBe(rect)
})
})
describe('mousedown()', function() {
it('attaches an onmousedown event to the node of the element', function() {
rect.mousedown(action)
expect(SVG.on).toHaveBeenCalledWith(rect.node, 'mousedown', action)
})
it('fires the event on mousedown', function() {
rect.mousedown(action).fire('mousedown')
expect(toast).toBe('ready')
})
it('applies the element as context', function() {
rect.mousedown(action).fire('mousedown')
expect(context).toBe(rect)
})
it('returns the called element', function() {
expect(rect.mousedown(action)).toBe(rect)
})
})
describe('mouseup()', function() {
it('attaches an onmouseup event to the node of the element', function() {
rect.mouseup(action)
expect(SVG.on).toHaveBeenCalledWith(rect.node, 'mouseup', action)
})
it('fires the event on mouseup', function() {
rect.mouseup(action).fire('mouseup')
expect(toast).toBe('ready')
})
it('applies the element as context', function() {
rect.mouseup(action).fire('mouseup')
expect(context).toBe(rect)
})
it('returns the called element', function() {
expect(rect.mouseup(action)).toBe(rect)
})
})
describe('mouseover()', function() {
it('attaches an onmouseover event to the node of the element', function() {
rect.mouseover(action)
expect(SVG.on).toHaveBeenCalledWith(rect.node, 'mouseover', action)
})
it('fires the event on mouseover', function() {
rect.mouseover(action).fire('mouseover')
expect(toast).toBe('ready')
})
it('applies the element as context', function() {
rect.mouseover(action).fire('mouseover')
expect(context).toBe(rect)
})
it('returns the called element', function() {
expect(rect.mouseover(action)).toBe(rect)
})
})
describe('mouseout()', function() {
it('attaches an onmouseout event to the node of the element', function() {
rect.mouseout(action)
expect(SVG.on).toHaveBeenCalledWith(rect.node, 'mouseout', action)
})
it('fires the event on mouseout', function() {
rect.mouseout(action).fire('mouseout')
expect(toast).toBe('ready')
})
it('applies the element as context', function() {
rect.mouseout(action).fire('mouseout')
expect(context).toBe(rect)
})
it('returns the called element', function() {
expect(rect.mouseout(action)).toBe(rect)
})
})
describe('mousemove()', function() {
it('attaches an onmousemove event to the node of the element', function() {
rect.mousemove(action)
expect(SVG.on).toHaveBeenCalledWith(rect.node, 'mousemove', action)
})
it('fires the event on mousemove', function() {
rect.mousemove(action).fire('mousemove')
expect(toast).toBe('ready')
})
it('applies the element as context', function() {
rect.mousemove(action).fire('mousemove')
expect(context).toBe(rect)
})
it('returns the called element', function() {
expect(rect.mousemove(action)).toBe(rect)
})
})
/*describe('mouseenter()', function() {
it('attaches an onmouseenter event to the node of the element', function() {
expect(typeof rect.node.onmouseenter).not.toBe('function')
rect.mouseenter(action)
expect(typeof rect.node.onmouseenter).toBe('function')
})
it('fires the event on mouseenter', function() {
rect.mouseenter(action).fire('mouseenter')
expect(toast).toBe('ready')
})
it('applies the element as context', function() {
rect.mouseenter(action).fire('mouseenter')
expect(context).toBe(rect)
})
it('returns the called element', function() {
expect(rect.mouseenter(action)).toBe(rect)
})
})
describe('mouseleave()', function() {
it('attaches an onmouseleave event to the node of the element', function() {
expect(typeof rect.node.onmouseleave).not.toBe('function')
rect.mouseleave(action)
expect(typeof rect.node.onmouseleave).toBe('function')
})
it('fires the event on mouseleave', function() {
rect.mouseleave(action).fire('mouseleave')
expect(toast).toBe('ready')
})
it('applies the element as context', function() {
rect.mouseleave(action).fire('mouseleave')
expect(context).toBe(rect)
})
it('returns the called element', function() {
expect(rect.mouseleave(action)).toBe(rect)
})
})*/
} else {
describe('touchstart()', function() {
it('attaches an ontouchstart event to the node of the element', function() {
rect.touchstart(action)
expect(SVG.on).toHaveBeenCalledWith(rect.node, 'touchstart', action)
})
it('fires the event on touchstart', function() {
rect.touchstart(action).fire('touchstart')
expect(toast).toBe('ready')
})
it('applies the element as context', function() {
rect.touchstart(action).fire('touchstart')
expect(context).toBe(rect)
})
it('returns the called element', function() {
expect(rect.touchstart(action)).toBe(rect)
})
})
describe('touchmove()', function() {
it('attaches an ontouchmove event to the node of the element', function() {
rect.touchmove(action)
expect(SVG.on).toHaveBeenCalledWith(rect.node, 'touchmove', action)
})
it('fires the event on touchmove', function() {
rect.touchmove(action).fire('touchmove')
expect(toast).toBe('ready')
})
it('applies the element as context', function() {
rect.touchmove(action).fire('touchmove')
expect(context).toBe(rect)
})
it('returns the called element', function() {
expect(rect.touchmove(action)).toBe(rect)
})
})
describe('touchleave()', function() {
it('attaches an ontouchleave event to the node of the element', function() {
rect.touchleave(action)
expect(SVG.on).toHaveBeenCalledWith(rect.node, 'touchleave', action)
})
it('fires the event on touchleave', function() {
rect.touchleave(action).fire('touchleave')
expect(toast).toBe('ready')
})
it('applies the element as context', function() {
rect.touchleave(action).fire('touchleave')
expect(context).toBe(rect)
})
it('returns the called element', function() {
expect(rect.touchleave(action)).toBe(rect)
})
})
describe('touchend()', function() {
it('attaches an ontouchend event to the node of the element', function() {
rect.touchend(action)
expect(SVG.on).toHaveBeenCalledWith(rect.node, 'touchend', action)
})
it('fires the event on touchend', function() {
rect.touchend(action).fire('touchend')
expect(toast).toBe('ready')
})
it('applies the element as context', function() {
rect.touchend(action).fire('touchend')
expect(context).toBe(rect)
})
it('returns the called element', function() {
expect(rect.touchend(action)).toBe(rect)
})
})
describe('touchcancel()', function() {
it('attaches an ontouchcancel event to the node of the element', function() {
rect.touchcancel(action)
expect(SVG.on).toHaveBeenCalledWith(rect.node, 'touchcancel', action)
})
it('fires the event on touchcancel', function() {
rect.touchcancel(action).fire('touchcancel')
expect(toast).toBe('ready')
})
it('applies the element as context', function() {
rect.touchcancel(action).fire('touchcancel')
expect(context).toBe(rect)
})
it('returns the called element', function() {
expect(rect.touchcancel(action)).toBe(rect)
})
})
}
describe('on()', function() {
it('attaches an event to the element', function() {
rect.on('event', action).fire('event')
expect(toast).toBe('ready')
})
it('attaches an event to a non svg element', function() {
var el = document.createElement('div')
SVG.on(el, 'event', action)
el.dispatchEvent(new window.CustomEvent('event'))
expect(toast).toBe('ready')
SVG.off(el, 'event', action)
})
it('attaches multiple handlers on different element', function() {
var listenerCnt = SVG.listeners.length
var rect2 = draw.rect(100,100);
var rect3 = draw.rect(100,100);
rect.on('event', action)
rect2.on('event', action)
rect3.on('event', function(){ butter = 'melting' })
rect3.on('event', action)
expect(Object.keys(SVG.listeners[SVG.handlerMap.indexOf(rect.node)]['event']['*']).length).toBe(1) // 1 listener on rect
expect(Object.keys(SVG.listeners[SVG.handlerMap.indexOf(rect2.node)]['event']['*']).length).toBe(1) // 1 listener on rect2
expect(Object.keys(SVG.listeners[SVG.handlerMap.indexOf(rect3.node)]['event']['*']).length).toBe(2) // 2 listener on rect3
expect(SVG.listeners.length).toBe(listenerCnt + 3) // added listeners on 3 different elements
})
if('attaches a handler to a namespaced event', function(){
var listenerCnt = SVG.listeners.length
var rect2 = draw.rect(100,100);
var rect3 = draw.rect(100,100);
rect.on('event.namespace1', action)
rect2.on('event.namespace2', action)
rect3.on('event.namespace3', function(){ butter = 'melting' })
rect3.on('event', action)
expect(Object.keys(SVG.listeners[SVG.handlerMap.indexOf(rect.node)]['event']['*'])).toBeUndefined() // no global listener on rect
expect(Object.keys(SVG.listeners[SVG.handlerMap.indexOf(rect.node)]['event']['namespace1']).length).toBe( 1) // 1 namespaced listener on rect
expect(Object.keys(SVG.listeners[SVG.handlerMap.indexOf(rect2.node)]['event']['namespace2']).length).toBe(1) // 1 namespaced listener on rect
expect(Object.keys(SVG.listeners[SVG.handlerMap.indexOf(rect3.node)]['event']['*']).length).toBe(1) // 1 gobal listener on rect3
expect(Object.keys(SVG.listeners[SVG.handlerMap.indexOf(rect3.node)]['event']['namespace3']).length).toBe(1) // 1 namespaced listener on rect3
expect(SVG.listeners.length).toBe(listenerCnt + 3) // added listeners on 3 different elements
})
it('applies the element as context', function() {
rect.on('event', action).fire('event')
expect(context).toBe(rect)
})
it('applies given object as context', function() {
rect.on('event', action, this).fire('event')
expect(context).toBe(this)
})
it('stores the listener for future reference', function() {
rect.on('event', action)
expect(SVG.listeners[SVG.handlerMap.indexOf(rect.node)]['event']['*'][action._svgjsListenerId]).not.toBeUndefined()
})
it('returns the called element', function() {
expect(rect.on('event', action)).toBe(rect)
})
})
describe('off()', function() {
var butter = null
beforeEach(function() {
butter = null
})
it('detaches a specific event listener, all other still working', function() {
rect2 = draw.rect(100,100);
rect3 = draw.rect(100,100);
rect.on('event', action)
rect2.on('event', action)
rect3.on('event', function(){ butter = 'melting' })
rect.off('event', action)
expect(Object.keys(SVG.listeners[SVG.handlerMap.indexOf(rect.node)]['event']['*']).length).toBe(0)
rect.fire('event')
expect(toast).toBeNull()
rect2.fire('event')
expect(toast).toBe('ready')
rect3.fire('event')
expect(butter).toBe('melting')
expect(SVG.listeners[SVG.handlerMap.indexOf(rect.node)]['event']['*'][action]).toBeUndefined()
})
it('detaches a specific namespaced event listener, all other still working', function() {
rect2 = draw.rect(100,100);
rect3 = draw.rect(100,100);
rect.on('event.namespace', action)
rect2.on('event.namespace', action)
rect3.on('event.namespace', function(){ butter = 'melting' })
rect.off('event.namespace', action)
expect(Object.keys(SVG.listeners[SVG.handlerMap.indexOf(rect.node)]['event']['namespace']).length).toBe(0)
rect.fire('event')
expect(toast).toBeNull()
rect2.fire('event')
expect(toast).toBe('ready')
rect3.fire('event')
expect(butter).toBe('melting')
expect(SVG.listeners[SVG.handlerMap.indexOf(rect.node)]['event']['namespace'][action]).toBeUndefined()
})
it('detaches all listeners for a specific namespace', function() {
rect.on('event', action)
rect.on('event.namespace', function() { butter = 'melting'; })
rect.off('.namespace')
rect.fire('event')
expect(toast).toBe('ready')
expect(butter).toBeNull()
})
it('detaches all listeners for an event without a listener given', function() {
rect.on('event', action)
rect.on('event.namespace', function() { butter = 'melting'; })
rect.off('event')
rect.fire('event')
expect(toast).toBeNull()
expect(butter).toBeNull()
expect(SVG.listeners[SVG.handlerMap.indexOf(rect.node)]['event']).toBeUndefined()
})
it('detaches all listeners without an argument', function() {
rect.on('event', action)
rect.on('click', function() { butter = 'melting' })
rect.off()
rect.fire('event')
rect.fire('click')
expect(toast).toBeNull()
expect(butter).toBeNull()
expect(SVG.listeners[SVG.handlerMap.indexOf(rect.node)]).toBeUndefined()
})
it('returns the called element', function() {
expect(rect.off('event', action)).toBe(rect)
})
it('does not throw when event is removed which was already removed with a global off', function() {
var undefined
rect.on('event', action)
rect.off()
try{
rect.off('event')
}catch(e){
expect('Should not error out').toBe(true)
}
expect(SVG.handlerMap[SVG.handlerMap.indexOf(rect.node)]).toBe(undefined)
})
})
describe('fire()', function() {
beforeEach(function() {
rect.on('event', action)
})
it('fires an event for the element', function() {
expect(toast).toBeNull()
rect.fire('event')
expect(toast).toBe('ready')
expect(fruitsInDetail).toBe(null)
})
it('returns the called element', function() {
expect(rect.fire('event')).toBe(rect)
})
it('fires event with additional data', function() {
expect(fruitsInDetail).toBeNull()
rect.fire('event', {apple:1})
expect(fruitsInDetail).not.toBe(null)
expect(fruitsInDetail.apple).toBe(1)
})
it('fires my own event', function() {
toast = null
rect.fire(new window.CustomEvent('event'))
expect(toast).toBe('ready')
})
it('makes the event cancelable', function() {
rect.on('event', function(e) {
e.preventDefault()
})
rect.fire('event')
expect(rect._event.defaultPrevented).toBe(true)
})
})
describe('event()', function() {
it('returns null when no event was fired', function() {
expect(rect.event()).toBe(null)
})
it('returns the last fired event', function() {
var event = new window.CustomEvent('foo')
rect.fire(event)
expect(rect.event()).toBe(event)
event = new window.CustomEvent('bar')
rect.fire(event)
expect(rect.event()).toBe(event)
})
})
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 | 2 | describe('FX', function() {
var rect, fx, undefined;
beforeEach(function() {
rect = draw.rect(100,100).move(100,100)
fx = rect.animate(500)
jasmine.clock().install()
jasmine.clock().mockDate() // This freeze the Date
})
afterEach(function() {
jasmine.clock().uninstall()
fx.stop(false, true)
})
it('creates an instance of SVG.FX and sets parameter', function() {
expect(fx instanceof SVG.FX).toBe(true)
expect(fx._target).toBe(rect)
expect(fx.absPos).toBe(0)
expect(fx.pos).toBe(0)
expect(fx.lastPos).toBe(0)
expect(fx.paused).toBe(false)
expect(fx.active).toBe(false)
expect(fx._speed).toBe(1)
expect(fx.situations).toEqual([])
expect(fx.situation.init).toBe(false)
expect(fx.situation.reversed).toBe(false)
expect(fx.situation.duration).toBe(500)
expect(fx.situation.delay).toBe(0)
expect(fx.situation.loops).toBe(false)
expect(fx.situation.loop).toBe(0)
expect(fx.situation.animations).toEqual({})
expect(fx.situation.attrs).toEqual({})
expect(fx.situation.styles).toEqual({})
expect(fx.situation.transforms).toEqual([])
expect(fx.situation.once).toEqual({})
})
describe('animate()', function () {
it('set duration, ease and delay of the new situation to their default value when they are not passed', function() {
var defaultDuration = 1000
, defaultEase = SVG.easing['-']
, defaultDelay = 0
, lastSituation = fx.animate().last()
expect(lastSituation.duration).toBe(defaultDuration)
expect(lastSituation.ease).toBe(defaultEase)
expect(lastSituation.delay).toBe(defaultDelay)
})
it('use the passed values to set duration, ease and delay of the new situation', function() {
var duration = 14502
, ease = '>'
, delay = 450
, lastSituation = fx.animate(duration, ease, delay).last()
expect(lastSituation.duration).toBe(duration)
expect(lastSituation.ease).toBe(SVG.easing[ease])
expect(lastSituation.delay).toBe(delay)
})
it('allow duration, ease and delay to be passed in an object', function() {
var o = {
duration: 7892
, ease: '<'
, delay: 1145
}
, lastSituation = fx.animate(o).last()
expect(lastSituation.duration).toBe(o.duration)
expect(lastSituation.ease).toBe(SVG.easing[o.ease])
expect(lastSituation.delay).toBe(o.delay)
})
it('allow ease to be a custom function', function () {
var customEase = function() {}
, lastSituation = fx.animate({ease: customEase}).last()
expect(lastSituation.ease).toBe(customEase)
})
})
describe('target()', function(){
it('returns the current fx object with no argument given', function(){
expect(fx.target()).toBe(rect)
})
it('changes the target of the animation when parameter given', function(){
var c = draw.circle(5)
expect(fx.target(c).target()).toBe(c)
})
})
describe('timeToAbsPos()', function() {
it('converts a timestamp to an absolute progress', function() {
expect(fx.timeToAbsPos( fx.situation.start + fx.situation.duration*0.5 )).toBe(0.5)
})
it('should take speed into consideration', function() {
var spd
spd = 4
fx.speed(spd)
expect(fx.timeToAbsPos( fx.situation.start + (fx.situation.duration/spd)*0.5 )).toBe(0.5)
spd = 0.5
fx.speed(spd)
expect(fx.timeToAbsPos( fx.situation.start + (fx.situation.duration/spd)*0.25 )).toBe(0.25)
})
})
describe('absPosToTime()', function() {
it('converts an absolute progress to a timestamp', function() {
expect(fx.absPosToTime(0.5)).toBe( fx.situation.start + fx.situation.duration*0.5 )
})
it('should take speed into consideration', function() {
var spd
spd = 4
fx.speed(spd)
expect(fx.absPosToTime(0.5)).toBe( fx.situation.start + (fx.situation.duration/spd)*0.5 )
spd = 0.5
fx.speed(spd)
expect(fx.absPosToTime(0.25)).toBe( fx.situation.start + (fx.situation.duration/spd)*0.25 )
})
})
describe('atStart()', function () {
it('sets the animation at the start', function() {
// When the animation is running forward, the start position is 0
fx.pos = 0.5
expect(fx.atStart().pos).toBe(0)
// When the animation is running backward, the start position is 1
fx.pos = 0.5
expect(fx.reverse(true).atStart().pos).toBe(1)
})
it('sets the animation at the start, before any loops', function() {
fx.loop(true)
// When the animation is running forward, the start position is 0
fx.at(3.7, true)
expect(fx.absPos).toBe(3.7)
expect(fx.pos).toBeCloseTo(0.7)
expect(fx.situation.loop).toBe(3)
fx.atStart()
expect(fx.absPos).toBe(0)
expect(fx.pos).toBe(0)
expect(fx.situation.loop).toBe(0)
// When the animation is running backward, the start position is 1
fx.reverse(true).at(2.14, true)
expect(fx.absPos).toBe(2.14)
expect(fx.pos).toBeCloseTo(1 - 0.14)
expect(fx.situation.loop).toBe(2)
expect(fx.situation.reversed).toBe(true)
fx.atStart()
expect(fx.absPos).toBe(0)
expect(fx.pos).toBe(1)
expect(fx.situation.loop).toBe(0)
expect(fx.situation.reversed).toBe(true)
})
it('sets the animation at the start, before any loops when reversing is true', function() {
fx.loop(true, true) // Set reversing to true
// When the animation is running forward, the start position is 0
fx.at(11.21, true)
expect(fx.absPos).toBe(11.21)
expect(fx.pos).toBeCloseTo(1 - 0.21)
expect(fx.situation.loop).toBe(11)
expect(fx.situation.reversed).toBe(true)
fx.atStart()
expect(fx.absPos).toBe(0)
expect(fx.pos).toBe(0)
expect(fx.situation.loop).toBe(0)
expect(fx.situation.reversed).toBe(false)
// When the animation is running backward, the start position is 1
fx.reverse(true).at(14.10, true)
expect(fx.absPos).toBe(14.10)
expect(fx.pos).toBeCloseTo(1 - 0.10)
expect(fx.situation.loop).toBe(14)
expect(fx.situation.reversed).toBe(true)
fx.atStart()
expect(fx.absPos).toBe(0)
expect(fx.pos).toBe(1)
expect(fx.situation.loop).toBe(0)
expect(fx.situation.reversed).toBe(true)
})
})
describe('atEnd()', function () {
it('sets the animation at the end', function() {
// When the animation is running forward, the end position is 1
fx.pos = 0.5
expect(fx.atEnd().pos).toBe(1)
expect(fx.situation).toBeNull()
// Recreate an animation since the other one was ended
fx.animate()
// When the animation is running backward, the end position is 0
fx.pos = 0.5
expect(fx.reverse(true).atEnd().pos).toBe(0)
expect(fx.situation).toBeNull()
})
it('sets the animation at the end, after all loops', function() {
var loops
// When the animation is running forward, the end position is 1
loops = 12
fx.loop(loops).start().step()
expect(fx.absPos).toBe(0)
expect(fx.pos).toBe(0)
expect(fx.active).toBe(true)
expect(fx.situation.loop).toBe(0)
expect(fx.situation.loops).toBe(loops)
fx.atEnd()
expect(fx.absPos).toBe(loops)
expect(fx.pos).toBe(1)
expect(fx.active).toBe(false)
expect(fx.situation).toBeNull()
// Recreate an animation since the other one was ended
fx.animate()
// When the animation is running backward, the end position is 0
loops = 21
fx.reverse(true).loop(loops).start().step()
expect(fx.absPos).toBe(0)
expect(fx.pos).toBe(1)
expect(fx.active).toBe(true)
expect(fx.situation.loop).toBe(0)
expect(fx.situation.loops).toBe(loops)
expect(fx.situation.reversed).toBe(true)
fx.atEnd()
expect(fx.absPos).toBe(loops)
expect(fx.pos).toBe(0)
expect(fx.active).toBe(false)
expect(fx.situation).toBeNull()
})
it('sets the animation at the end, after all loops when reversing is true', function() {
var loops
// When reversing is true, the end position is 0 when loops is even and
// 1 when loops is odd
// The animation is running forward
loops = 6
fx.loop(loops, true).start().step()
expect(fx.absPos).toBe(0)
expect(fx.pos).toBe(0)
expect(fx.active).toBe(true)
expect(fx.situation.loop).toBe(0)
expect(fx.situation.loops).toBe(loops)
expect(fx.situation.reversed).toBe(false)
fx.atEnd()
expect(fx.absPos).toBe(loops)
expect(fx.pos).toBe(0) // End position is 0 because loops is even
expect(fx.active).toBe(false)
expect(fx.situation).toBeNull()
// Recreate an animation since the other one was ended
fx.animate()
// When reversing is true and the animation is running backward,
// the end position is 1 when loops is even and 0 when loops is odd
// The animation is running backward
loops = 3
fx.reverse(true).loop(loops, true).start().step()
expect(fx.absPos).toBe(0)
expect(fx.pos).toBe(1)
expect(fx.active).toBe(true)
expect(fx.situation.loop).toBe(0)
expect(fx.situation.loops).toBe(loops)
expect(fx.situation.reversed).toBe(true)
fx.atEnd()
expect(fx.absPos).toBe(loops)
expect(fx.pos).toBe(0) // End position is 0 because loops is odd
expect(fx.active).toBe(false)
expect(fx.situation).toBeNull()
})
it('sets the animation at the end of the current iteration when in an infinite loop', function () {
// When the animation is running forward, the end position is 1
fx.loop(true).start().step()
expect(fx.absPos).toBe(0)
expect(fx.pos).toBe(0)
expect(fx.active).toBe(true)
expect(fx.situation.loop).toBe(0)
expect(fx.situation.loops).toBe(true)
// Should be halfway through iteration 10
jasmine.clock().tick(500 * 10 + 250)
fx.step()
expect(fx.absPos).toBe(10.5)
expect(fx.pos).toBe(0.5)
expect(fx.active).toBe(true)
expect(fx.situation.loop).toBe(10)
expect(fx.situation.loops).toBe(true)
fx.atEnd()
expect(fx.absPos).toBe(11)
expect(fx.pos).toBe(1)
expect(fx.active).toBe(false)
expect(fx.situation).toBeNull()
// Recreate an animation since the other one was ended
fx.animate(500)
// When the animation is running backward, the end position is 0
fx.reverse(true).loop(true).start().step()
expect(fx.absPos).toBe(0)
expect(fx.pos).toBe(1)
expect(fx.active).toBe(true)
expect(fx.situation.loop).toBe(0)
expect(fx.situation.loops).toBe(true)
expect(fx.situation.reversed).toBe(true)
// Should be halfway through iteration 21
jasmine.clock().tick(500 * 21 + 250)
fx.step()
expect(fx.absPos).toBe(21.5)
expect(fx.pos).toBe(0.5)
expect(fx.active).toBe(true)
expect(fx.situation.loop).toBe(21)
expect(fx.situation.loops).toBe(true)
fx.atEnd()
expect(fx.absPos).toBe(22)
expect(fx.pos).toBe(0)
expect(fx.active).toBe(false)
expect(fx.situation).toBeNull()
})
it('sets the animation at the end of the current iteration when in an infinite loop and reversing is true', function () {
// When reversing is true, the end position is 1 when ending on an even
// iteration and 0 when ending on an odd iteration as illustrated below:
// 0 Iteration 1
// |--------------0------------->|
// |<-------------1--------------|
// |--------------2------------->|
// |<-------------3--------------|
// ...
// The animation is running forward
fx.loop(true, true).start().step()
expect(fx.absPos).toBe(0)
expect(fx.pos).toBe(0)
expect(fx.active).toBe(true)
expect(fx.situation.loop).toBe(0)
expect(fx.situation.loops).toBe(true)
// Should be halfway through iteration 11
jasmine.clock().tick(500 * 11 + 250)
fx.step()
expect(fx.absPos).toBe(11.5)
expect(fx.pos).toBe(0.5)
expect(fx.active).toBe(true)
expect(fx.situation.loop).toBe(11)
expect(fx.situation.loops).toBe(true)
fx.atEnd()
expect(fx.absPos).toBe(12)
expect(fx.pos).toBe(0) // End position is 0 because ended on a odd iteration
expect(fx.active).toBe(false)
expect(fx.situation).toBeNull()
// Recreate an animation since the other one was ended
fx.animate(500)
// When reversing is true and the animation is running backward,
// the end position is 0 when ending on an even iteration and
// 1 when ending on an odd iteration as illustrated below:
// 0 Iteration 1
// |<-------------0--------------|
// |--------------1------------->|
// |<-------------2--------------|
// |--------------3------------->|
// ...
// The animation is running backward
fx.reverse(true).loop(true).start().step()
expect(fx.absPos).toBe(0)
expect(fx.pos).toBe(1)
expect(fx.active).toBe(true)
expect(fx.situation.loop).toBe(0)
expect(fx.situation.loops).toBe(true)
expect(fx.situation.reversed).toBe(true)
// Should be halfway through iteration 42
jasmine.clock().tick(500 * 42 + 250)
fx.step()
expect(fx.absPos).toBe(42.5)
expect(fx.pos).toBe(0.5)
expect(fx.active).toBe(true)
expect(fx.situation.loop).toBe(42)
expect(fx.situation.loops).toBe(true)
fx.atEnd()
expect(fx.absPos).toBe(43)
expect(fx.pos).toBe(0) // End position is 0 because ended on an even iteration
expect(fx.active).toBe(false)
expect(fx.situation).toBeNull()
})
})
describe('at()', function() {
it('sets the progress to the specified position', function() {
var pos
// Animation running forward
pos = 0.5
expect(fx.at(pos).pos).toBe(pos)
expect(fx.situation.start).toBe(+new Date - fx.situation.duration * pos)
// Animation running backward
pos = 0.4
expect(fx.reverse(true).at(pos).pos).toBe(pos)
expect(fx.situation.start).toBe(+new Date - fx.situation.duration * (1-pos))
})
it('should convert a position to an absolute position', function () {
var pos, loop, absPos
fx.loop(true)
// Animation running forward
pos = 0.7
loop = 4
absPos = pos+loop
fx.situation.loop = loop
expect(fx.at(pos).absPos).toBe(absPos)
expect(fx.situation.start).toBe(+new Date - fx.situation.duration * absPos)
// Animation running backward
pos = 0.23
loop = 9
absPos = (1-pos)+loop
fx.situation.loop = loop
fx.situation.reversed = true
expect(fx.at(pos).absPos).toBe(absPos)
expect(fx.situation.start).toBe(+new Date - fx.situation.duration * absPos)
})
it('should end the animation when the end position is passed', function() {
var pos
fx.start()
expect(fx.active).toBe(true)
expect(fx.situation).not.toBeNull()
// When running forward, the end position is 1
pos = 1
expect(fx.at(pos).pos).toBe(pos)
expect(fx.active).toBe(false)
expect(fx.situation).toBeNull()
// Recreate an animation since the other one was ended
fx.animate().start()
expect(fx.active).toBe(true)
expect(fx.situation).not.toBeNull()
// When running backward, the end position is 0
pos = 0
expect(fx.reverse(true).at(pos).pos).toBe(pos)
expect(fx.active).toBe(false)
expect(fx.situation).toBeNull()
})
it('correct the passed position when it is out of [0,1] and the animation is not looping', function () {
var pos
pos = -0.7
expect(fx.at(pos).pos).toBe(0)
pos = 1.3
expect(fx.at(pos).pos).toBe(1)
// Recreate an animation since the other one was ended
fx.animate()
// Should work even when animation is running backward
pos = 1.3
expect(fx.reverse(true).at(pos).pos).toBe(1)
pos = -0.7
expect(fx.reverse(true).at(pos).pos).toBe(0)
})
it('should, when the animation is looping and the passed position is out of [0,1], use the integer part of postion to update the loop counter and set position to its fractional part', function(){
var loop, pos, posFrac, posInt
// Without the reverse flag
fx.loop(10)
expect(fx.situation.loops).toBe(10)
expect(fx.situation.loop).toBe(loop = 0)
pos = 1.3
posFrac = pos % 1
posInt = pos - posFrac
expect(fx.at(pos).pos).toBeCloseTo(posFrac)
expect(fx.situation.loop).toBe(loop += posInt)
pos = 7.723
posFrac = pos % 1
posInt = pos - posFrac
expect(fx.at(pos).pos).toBeCloseTo(posFrac)
expect(fx.situation.loop).toBe(loop += posInt)
// In this case, pos is above the remaining number of loops, so we expect
// the position to be set to 1 and the animation to be ended
pos = 4.3
posFrac = pos % 1
posInt = pos - posFrac
expect(fx.at(pos).pos).toBe(1)
expect(fx.situation).toBeNull()
// Recreate an animation since the other one was ended
fx.animate()
// With the reverse flag, the position is reversed each time loop is odd
fx.loop(10, true)
expect(fx.situation.loops).toBe(10)
expect(fx.situation.loop).toBe(loop = 0)
expect(fx.situation.reversed).toBe(false)
pos = 3.3
posFrac = pos % 1
posInt = pos - posFrac
expect(fx.at(pos).pos).toBeCloseTo(1-posFrac) // Animation is reversed because 0+3 is odd
expect(fx.situation.loop).toBe(loop += posInt)
expect(fx.situation.reversed).toBe(true)
// When the passed position is below 0, the integer part of position is
// substracted from 1, so, in this case, -0.6 has 1 as is integer part
// This is necessary so we can add something to the loop counter
pos = -0.645
posFrac = (1-pos) % 1
posInt = (1-pos) - posFrac
expect(fx.at(pos).pos).toBeCloseTo(posFrac)
expect(fx.situation.loop).toBe(loop += posInt)
expect(fx.situation.reversed).toBe(false)
// In this case, pos is above the remaining number of loop, so we expect
// the position to be set to 0 (since we end reversed) and the animation to
// be ended
pos = 7.2
posFrac = pos % 1
posInt = pos - posFrac
expect(fx.at(pos).pos).toBe(0)
expect(fx.situation).toBeNull()
})
it('should, when the animation is in a infinite loop and the passed position is out of [0,1], use the integer part of postion to update the loop counter and set position to its fractional part', function(){
var loop, pos, posFrac, posInt
// Without the reverse flag
fx.loop(true)
expect(fx.situation.loops).toBe(true)
expect(fx.situation.loop).toBe(loop = 0)
pos = 10.34
posFrac = pos % 1
posInt = pos - posFrac
expect(fx.at(pos).pos).toBeCloseTo(posFrac)
expect(fx.situation.loop).toBe(loop += posInt)
// With the reverse flag, the position is reversed each time loop is odd
fx.loop(true, true)
expect(fx.situation.loops).toBe(true)
expect(fx.situation.loop).toBe(loop = 0)
expect(fx.situation.reversed).toBe(false)
pos = 3.3
posFrac = pos % 1
posInt = pos - posFrac
expect(fx.at(pos).pos).toBeCloseTo(1-posFrac) // Animation is reversed because 3+0 is odd
expect(fx.situation.loop).toBe(loop += posInt)
expect(fx.situation.reversed).toBe(true)
pos = -8.41
posFrac = (1-pos) % 1
posInt = (1-pos) - posFrac
expect(fx.at(pos).pos).toBeCloseTo(posFrac)
expect(fx.situation.loop).toBe(loop += posInt)
expect(fx.situation.reversed).toBe(false)
})
it('should take speed into consideration', function() {
var dur, spd
dur = fx.situation.duration
spd = 4
fx.speed(spd).at(0)
expect(fx.situation.finish-fx.situation.start).toBe(dur/spd)
spd = 5
fx.speed(spd).at(0.15)
expect(fx.situation.finish-fx.situation.start).toBe(dur/spd)
spd = 0.25
fx.speed(spd).at(0.75)
expect(fx.situation.finish-fx.situation.start).toBe(dur/spd)
spd = 0.5
fx.speed(spd).at(0.83)
expect(fx.situation.finish-fx.situation.start).toBe(dur/spd)
})
it('should consider the first parameter as an absolute position when the second parameter is true', function() {
var absPos
fx.loop(true)
absPos = 3.2
expect(fx.at(absPos, true).absPos).toBe(absPos)
absPos = -4.27
expect(fx.at(absPos, true).absPos).toBe(absPos)
absPos = 0
expect(fx.at(absPos, true).absPos).toBe(absPos)
absPos = 1
expect(fx.at(absPos, true).absPos).toBe(absPos)
})
})
describe('start()', function(){
it('starts the animation', function() {
fx.start()
expect(fx.active).toBe(true)
jasmine.clock().tick(200)
fx.step() // Call step to update the animation
expect(fx.pos).toBeGreaterThan(0)
})
it('should take speed into consideration', function() {
var dur = 500
, delay = 300
, spd = 4
fx.stop().animate(dur, '-', delay).speed(spd).start()
expect(fx.situation.finish - new Date).toBe(delay/spd + dur/spd)
})
it('should do the delay', function() {
fx.situation.delay = 1000
expect(fx.start().active).toBe(true)
jasmine.clock().tick(501)
fx.step() // Call step to update the animation
expect(fx.active).toBe(true)
jasmine.clock().tick(501)
fx.step() // Call step to update the animation
expect(fx.active).toBe(true)
jasmine.clock().tick(501)
fx.step() // Call step to update the animation
expect(fx.active).toBe(false)
})
})
describe('delay()', function() {
it('should push an empty situation with its duration attribute set to the duration of the delay', function() {
var delay = 8300
fx.delay(delay)
expect(fx.situations[0].duration).toBe(delay)
})
})
describe('pause()', function() {
it('pause the animation', function() {
expect(fx.pause().paused).toBe(true)
})
})
describe('play()', function() {
it('returns itself when animation not paused', function() {
expect(fx.paused).toBe(false)
expect(fx.play()).toBe(fx)
})
it('unpause the animation', function() {
var start = fx.start().pause().situation.start
jasmine.clock().tick(200)
expect(fx.situation.start).toBe(start)
expect(fx.play().paused).toBe(false)
expect(fx.situation.start).not.toBe(start)
})
it('should not change the position when the animation is unpaused while it is set to run backward', function(){
var pos = 0.4
expect(fx.reverse(true).at(pos).pause().play().pos).toBe(pos)
})
it('should be able to unpause the delay', function () {
fx.stop().animate(500, '-', 300).start().step()
expect(fx.pos).toBe(0)
expect(fx.absPos).toBeCloseTo(-0.6)
// At this point, we should have an animation of 500 ms with a delay of
// 300 ms that should be running.
jasmine.clock().tick(150)
// Should be halfway through the delay
fx.step()
expect(fx.pos).toBe(0)
expect(fx.absPos).toBe(-0.3)
expect(fx.pause().paused).toBe(true) // Pause the delay
jasmine.clock().tick(150)
// Unpause, should still be halfway through the delay
expect(fx.play().paused).toBe(false)
expect(fx.pos).toBe(0)
expect(fx.absPos).toBe(-0.3)
jasmine.clock().tick(150)
// Delay should be done
fx.step()
expect(fx.pos).toBe(0)
expect(fx.absPos).toBe(0)
jasmine.clock().tick(500)
// Animation and delay should be done
fx.step()
expect(fx.active).toBe(false)
expect(fx.pos).toBe(1)
expect(fx.absPos).toBe(1)
})
})
describe('speed()', function() {
it('set the speed of the animation', function(){
var dur, spd
dur = fx.situation.duration
spd = 2
fx.speed(spd)
expect(fx._speed).toBe(spd)
expect(fx.situation.finish-fx.situation.start).toBe(dur/spd)
spd = 0.5
fx.speed(spd)
expect(fx._speed).toBe(spd)
expect(fx.situation.finish-fx.situation.start).toBe(dur/spd)
spd = 2
fx.at(0.2).speed(spd)
expect(fx._speed).toBe(spd)
expect(fx.situation.finish-fx.situation.start).toBe(dur/spd)
spd = 1
fx.speed(spd)
expect(fx._speed).toBe(spd)
expect(fx.situation.finish-fx.situation.start).toBe(dur)
})
it('should not change the position when the animation is run backward', function(){
var pos = 0.4
expect(fx.reverse(true).at(pos).speed(2).pos).toBe(pos)
})
it('return the current speed with no argument given', function(){
var spd
spd = 2
fx._speed = spd
expect(fx.speed()).toBe(spd)
spd = 0.5
fx._speed = spd
expect(fx.speed()).toBe(spd)
spd = 1
fx._speed = spd
expect(fx.speed()).toBe(spd)
})
it('pause the animation when a speed of 0 is passed', function(){
var spd = fx._speed
expect(fx.speed(0)).toBe(fx)
expect(fx._speed).toBe(spd)
expect(fx.paused).toBe(true)
})
it('should affect all animations in the queue', function(){
fx.speed(2).animate(300)
expect(fx.situations.length).not.toBe(0)
expect(fx.pos).not.toBe(1)
// At this point, there should be 2 animations in the queue to be played:
// the one of 500ms that is added before every test and the one of 300ms
// we just added. Normally, it would take 800ms before both of these
// animations are done, but because we set the speed to 2, it should
// only take 400ms to do both animations.
fx.start().step()
jasmine.clock().tick(250)
// Should be playing the second animation
fx.step()
expect(fx.active).toBe(true)
expect(fx.situations.length).toBe(0)
expect(fx.pos).not.toBe(1)
jasmine.clock().tick(150) // 400ms have passed
// All animations should be done
fx.step()
expect(fx.active).toBe(false)
expect(fx.situations.length).toBe(0)
expect(fx.pos).toBe(1)
})
it('should affect the delay', function() {
fx.stop().animate(500, '-', 300).start().step()
expect(fx.pos).toBe(0)
expect(fx.absPos).toBeCloseTo(-0.6)
fx.speed(2)
expect(fx.pos).toBe(0)
expect(fx.absPos).toBeCloseTo(-0.6)
// At this point, we should have an animation of 500 ms with a delay of
// 300 ms that should be running. Normally, it would take 800 ms for the
// animation and its delay to complete, but because the speed is set to 2
// , it should only take 400ms
jasmine.clock().tick(75)
// Should be halfway through the delay
fx.step()
expect(fx.pos).toBe(0)
expect(fx.absPos).toBe(-0.3)
jasmine.clock().tick(75)
// Delay should be done
fx.step()
expect(fx.pos).toBe(0)
expect(fx.absPos).toBe(0)
jasmine.clock().tick(250)
// Animation and delay should be done
fx.step()
expect(fx.active).toBe(false)
expect(fx.pos).toBe(1)
expect(fx.absPos).toBe(1)
})
})
describe('reverse()', function() {
it('toggles the direction of the animation without a parameter', function() {
expect(fx.reverse().situation.reversed).toBe(true)
})
it('sets the direction to backwards with true given', function() {
expect(fx.reverse(true).situation.reversed).toBe(true)
})
it('sets the direction to forwards with false given', function() {
expect(fx.reverse(false).situation.reversed).toBe(false)
})
})
describe('queue()', function() {
it('can add a situation to the queue', function() {
var situation = new SVG.Situation({duration: 1000, delay: 0, ease: SVG.easing['-']})
fx.queue(situation)
expect(fx.situations[0]).toBe(situation)
})
it('can add a function to the queue', function() {
var f = function(){}
fx.queue(f)
expect(fx.situations[0]).toBe(f)
})
it('should set the situation attribute before pushing something in the situations queue', function(){
var situation = new SVG.Situation({duration: 1000, delay: 0, ease: SVG.easing['-']})
// Clear the animation that is created before each test
fx.stop()
expect(fx.situation).toBeNull()
expect(fx.situations.length).toBe(0)
fx.queue(situation)
expect(fx.situation).toBe(situation)
expect(fx.situations.length).toBe(0)
})
})
describe('dequeue()', function() {
it('should pull the next situtation from the queue', function() {
var situation = new SVG.Situation({duration: 1000, delay: 0, ease: SVG.easing['-']})
fx.queue(situation)
expect(fx.situtation).not.toBe(situation)
expect(fx.situations[0]).toBe(situation)
fx.dequeue()
expect(fx.situation).toBe(situation)
expect(fx.situations.length).toBe(0)
})
it('initialize the animation pulled from the queue to its start position', function() {
// When the animation is forward, the start position is 0
fx.animate()
fx.pos = 0.5
expect(fx.dequeue().pos).toBe(0)
// When the animation backward, the start position is 1
fx.animate().reverse(true)
fx.pos = 0.5
expect(fx.dequeue().pos).toBe(1)
})
it('when the first element of the queue is a function, it should execute it', function() {
var called = false
fx.queue(function(){
called = true
expect(this).toBe(fx)
this.dequeue()
}).dequeue()
expect(called).toBe(true)
})
it('should stop the currently running animation when there is one', function() {
fx.start()
expect(fx.active).toBe(true)
fx.queue(function() {
expect(this.active).toBe(false)
this.dequeue()
})
fx.dequeue()
})
})
describe('stop()', function() {
it('stops the animation immediately without a parameter', function() {
fx.animate(500).start()
expect(fx.stop().situation).toBeNull()
expect(fx.active).toBe(false)
expect(fx.situations.length).toBe(1)
})
it('stops the animation immediately and fullfill it if first parameter true', function() {
fx.animate(500).start()
expect(fx.stop(true).situation).toBeNull()
expect(fx.active).toBe(false)
expect(fx.pos).toBe(1)
expect(fx.situations.length).toBe(1)
})
it('stops the animation immediately and remove all items from queue when second parameter true', function() {
fx.animate(500).start()
expect(fx.stop(false, true).situation).toBeNull()
expect(fx.active).toBe(false)
expect(fx.situations.length).toBe(0)
})
})
describe('reset()', function() {
it('resets the element to the state it was when the current animation was started', function() {
var loops = 4
, situation = fx.situation
// These settings make the animations run backward
fx.situation.loop = 2
fx.situation.loops = loops
fx.situation.reversed = true
fx.pos = 0.5
fx.absPos = 2.5
fx.reset()
expect(fx.situation).toBe(situation)
expect(fx.situation.loops).toBe(loops)
expect(fx.situation.loop).toBe(0)
expect(fx.situation.reversed).toBe(true) // True because the animation is backward
expect(fx.pos).toBe(1)
expect(fx.absPos).toBe(0)
})
})
describe('finish()', function() {
it('finish the whole animation by fullfilling every single one', function() {
fx.animate(500)
expect(fx.finish().pos).toBe(1)
expect(fx.situations.length).toBe(0)
expect(fx.situation).toBeNull()
})
})
describe('progress()', function() {
it('returns the current position', function() {
expect(fx.progress()).toBe(0)
expect(fx.progress()).toBe(fx.pos)
})
it('returns the current position as eased value if fist argument is true', function() {
var anim = draw.rect(100,100).animate(500,'>').start()
expect(anim.progress(true)).toBe(0)
anim.at(0.25)
expect(anim.progress(true)).toBeCloseTo(anim.situation.ease(0.25))
})
})
describe('after()', function() {
it('adds a callback which is called when the current animation is finished', function() {
var called = false
fx.start().after(function(situation){
expect(fx.situation).toBe(situation)
expect(fx.pos).toBe(1)
called = true
})
jasmine.clock().tick(500)
fx.step()
expect(called).toBe(true)
})
})
describe('afterAll()', function() {
it('adds a callback which is called when all animations are finished', function() {
var called = false
fx.animate(150).animate(125).start().afterAll(function(){
expect(fx.pos).toBe(1)
expect(fx.situations.length).toBe(0)
called = true
})
expect(fx.situations.length).toBe(2)
// End of the first animation
jasmine.clock().tick(500)
fx.step()
expect(fx.situations.length).toBe(1)
expect(called).toBe(false)
// End of the second animation
jasmine.clock().tick(150)
fx.step()
expect(fx.situations.length).toBe(0)
expect(called).toBe(false)
// End of the third and last animation
jasmine.clock().tick(125)
fx.step()
expect(fx.situation).toBeNull()
expect(called).toBe(true)
})
})
describe('during()', function() {
it('adds a callback which is called on every animation step', function() {
var called = 0
fx.start().during(function(pos, morph, eased, situation){
expect(fx.situation).toBe(situation)
switch(++called) {
case 1:
expect(pos).toBeCloseTo(0.25)
break
case 2:
expect(pos).toBeCloseTo(0.5)
break
case 3:
expect(pos).toBeCloseTo(0.65)
break
case 4:
expect(pos).toBe(1)
break
}
expect(morph(0, 100)).toBeCloseTo(pos*100)
})
jasmine.clock().tick(125)
fx.step()
expect(called).toBe(1)
jasmine.clock().tick(125) // 250 ms have passed
fx.step()
expect(called).toBe(2)
jasmine.clock().tick(75) // 325 ms have passed
fx.step()
expect(called).toBe(3)
jasmine.clock().tick(175) // 500 ms have passed
fx.step()
expect(called).toBe(4)
})
})
describe('duringAll()', function() {
it('adds a callback which is called on every animation step for the whole chain', function() {
fx.finish()
rect.off('.fx')
fx.animate(500).start().animate(500)
var sit = null
var pos1 = false
var pos2 = false
fx.duringAll(function(pos, morph, eased, situation){
if(pos1){
pos1 = false
sit = situation
expect(this.fx.pos).toBeCloseTo(0.6)
}
if(pos2){
pos2 = null
expect(situation).not.toBe(sit)
expect(this.fx.pos).toBeCloseTo(0.75)
}
})
pos1 = true
jasmine.clock().tick(300)
fx.step()
jasmine.clock().tick(200) // End of the first animation
fx.step()
pos2 = true
jasmine.clock().tick(375)
fx.step()
if(pos1 || pos2) {
fail('Not enough situations called')
}
})
})
describe('once()', function() {
it('adds a callback which is called once at the specified position', function() {
var called = false
fx.start().once(0.5, function(pos, eased){
called = true
expect(pos).toBeCloseTo(0.5)
})
jasmine.clock().tick(125)
fx.step()
expect(called).toBe(false)
jasmine.clock().tick(125) // 250 ms have passed
fx.step()
expect(called).toBe(true)
})
})
describe('loop()', function() {
it('should create an eternal loop when no arguments are given', function() {
var time = 10523, dur = fx.situation.duration
fx.loop()
expect(fx.situation.loop).toBe(0)
expect(fx.situation.loops).toBe(true)
expect(fx.pos).toBe(0)
expect(fx.absPos).toBe(0)
fx.start().step()
jasmine.clock().tick(time)
fx.step()
expect(fx.active).toBe(true)
expect(fx.situation.loop).toBe( Math.floor(time/dur) )
expect(fx.situation.loops).toBe(true)
expect(fx.pos).toBeCloseTo((time/dur) % 1)
expect(fx.absPos).toBeCloseTo(time/dur)
})
it('should create an eternal loop when the first argument is true', function() {
var time = 850452, dur = fx.situation.duration
fx.loop(true)
expect(fx.situation.loop).toBe(0)
expect(fx.situation.loops).toBe(true)
expect(fx.pos).toBe(0)
expect(fx.absPos).toBe(0)
fx.start().step()
jasmine.clock().tick(time)
fx.step()
expect(fx.active).toBe(true)
expect(fx.situation.loop).toBe( Math.floor(time/dur) )
expect(fx.situation.loops).toBe(true)
expect(fx.pos).toBeCloseTo((time/dur) % 1)
expect(fx.absPos).toBeCloseTo(time/dur)
})
it('should loop for the specified number of times', function() {
var time = 0, dur = fx.situation.duration
fx.loop(3)
expect(fx.situation.loop).toBe(0)
expect(fx.situation.loops).toBe(3)
expect(fx.pos).toBe(0)
expect(fx.absPos).toBe(0)
fx.start().step()
jasmine.clock().tick(200)
time = 200
fx.step()
expect(fx.active).toBe(true)
expect(fx.situation.loop).toBe(0)
expect(fx.situation.loops).toBe(3)
expect(fx.pos).toBeCloseTo((time/dur) % 1)
expect(fx.absPos).toBeCloseTo(time/dur)
jasmine.clock().tick(550)
time += 550 // time at 750
fx.step()
expect(fx.active).toBe(true)
expect(fx.situation.loop).toBe(1)
expect(fx.situation.loops).toBe(3)
expect(fx.pos).toBeCloseTo((time/dur) % 1)
expect(fx.absPos).toBeCloseTo(time/dur)
jasmine.clock().tick(570)
time += 570 // time at 1320
fx.step()
expect(fx.active).toBe(true)
expect(fx.situation.loop).toBe(2)
expect(fx.situation.loops).toBe(3)
expect(fx.pos).toBeCloseTo((time/dur) % 1)
expect(fx.absPos).toBeCloseTo(time/dur)
jasmine.clock().tick(180)
time += 180 // time at 1500
fx.step()
expect(fx.active).toBe(false)
expect(fx.situation).toBeNull()
expect(fx.pos).toBe(1)
expect(fx.absPos).toBe(3)
})
it('should go from beginning to end and start over again (0->1.0->1.0->1.) by default', function() {
var time = 0, dur = fx.situation.duration
fx.loop(2)
expect(fx.situation.loop).toBe(0)
expect(fx.situation.loops).toBe(2)
expect(fx.situation.reversing).toBe(false)
expect(fx.situation.reversed).toBe(false)
expect(fx.pos).toBe(0)
expect(fx.absPos).toBe(0)
fx.start().step()
jasmine.clock().tick(325)
time = 325
fx.step()
expect(fx.active).toBe(true)
expect(fx.situation.loop).toBe(0)
expect(fx.situation.loops).toBe(2)
expect(fx.situation.reversing).toBe(false)
expect(fx.situation.reversed).toBe(false)
expect(fx.pos).toBeCloseTo((time/dur) % 1)
expect(fx.absPos).toBeCloseTo(time/dur)
jasmine.clock().tick(575)
time += 575 // time at 900
fx.step()
expect(fx.active).toBe(true)
expect(fx.situation.loop).toBe(1)
expect(fx.situation.loops).toBe(2)
expect(fx.situation.reversing).toBe(false)
expect(fx.situation.reversed).toBe(false)
expect(fx.pos).toBeCloseTo((time/dur) % 1)
expect(fx.absPos).toBeCloseTo(time/dur)
jasmine.clock().tick(200)
time += 200 // time at 1100
fx.step()
expect(fx.active).toBe(false)
expect(fx.situation).toBeNull()
expect(fx.pos).toBe(1)
expect(fx.absPos).toBe(2)
})
it('should be completely reversed before starting over (0->1->0->1->0->1.) when the reverse flag is passed', function() {
var time = 0, dur = fx.situation.duration
fx.loop(2, true)
expect(fx.situation.loop).toBe(0)
expect(fx.situation.loops).toBe(2)
expect(fx.situation.reversing).toBe(true)
expect(fx.situation.reversed).toBe(false)
expect(fx.pos).toBe(0)
expect(fx.absPos).toBe(0)
fx.start().step()
jasmine.clock().tick(325)
time = 325
fx.step()
expect(fx.active).toBe(true)
expect(fx.situation.loop).toBe(0)
expect(fx.situation.loops).toBe(2)
expect(fx.situation.reversing).toBe(true)
expect(fx.situation.reversed).toBe(false)
expect(fx.pos).toBeCloseTo((time/dur) % 1)
expect(fx.absPos).toBeCloseTo(time/dur)
jasmine.clock().tick(575)
time += 575 // time at 900
fx.step()
expect(fx.active).toBe(true)
expect(fx.situation.loop).toBe(1)
expect(fx.situation.loops).toBe(2)
expect(fx.situation.reversing).toBe(true)
expect(fx.situation.reversed).toBe(true)
expect(fx.pos).toBeCloseTo(1 - (time/dur) % 1)
expect(fx.absPos).toBeCloseTo(time/dur)
jasmine.clock().tick(200)
time += 200 // time at 1100
fx.step()
expect(fx.active).toBe(false)
expect(fx.situation).toBeNull()
expect(fx.pos).toBe(0)
expect(fx.absPos).toBe(2)
})
it('should be applied on the last situation', function() {
fx.loop(5)
expect(fx.situation.loop).toBe(0)
expect(fx.situation.loops).toBe(5)
expect(fx.situation.reversing).toBe(false)
fx.animate().loop(3, true)
expect(fx.situation.loop).toBe(0)
expect(fx.situation.loops).toBe(5)
expect(fx.situation.reversing).toBe(false)
var c = fx.last()
expect(c.loop).toBe(0)
expect(c.loops).toBe(3)
expect(c.reversing).toBe(true)
})
it('should be possible to call it with false as the first argument', function() {
fx.situation.loops = true
fx.loop(false)
expect(fx.situation.loops).toBe(false)
})
})
describe('step()', function() {
it('should not recalculate the absolute position if the first parameter is true', function() {
var absPos
// We shift start to help us see if the absolute position get recalculated
// If it get recalculated, the result would be 0.5
fx.situation.start -= 250
absPos = 0.4
fx.absPos = absPos
expect(fx.step(true).absPos).toBe(absPos)
absPos = 0
fx.absPos = absPos
expect(fx.step(true).absPos).toBe(absPos)
absPos = -3.7
fx.absPos = absPos
expect(fx.step(true).absPos).toBe(absPos)
absPos = 1
fx.absPos = absPos
expect(fx.step(true).absPos).toBe(absPos)
})
it('should not allow an absolute position to be above the end', function() {
var absPos, loops
// With no loops, absolute position should not go above 1
absPos = 4.26
fx.absPos = absPos
expect(fx.step(true).absPos).toBe(1)
expect(fx.situation).toBeNull()
fx.animate() // Recreate an animation since the other one was ended
// With loops, absolute position should not go above loops
loops = 4
absPos = 7.42
fx.absPos = absPos
expect(fx.loop(loops).step(true).absPos).toBe(loops)
expect(fx.situation).toBeNull()
})
describe('when converting an absolute position to a position', function() {
it('should, when the absolute position is below the maximum number of loops, use the integer part of the absolute position to set the loop counter and use its fractional part to set the position', function(){
var absPos, absPosFrac, absPosInt, loops
// Without the reverse flag
loops = 12
absPos = 4.52
absPosInt = Math.floor(absPos)
absPosFrac = absPos - absPosInt
fx.absPos = absPos
fx.loop(loops).step(true)
expect(fx.pos).toBe(absPosFrac)
expect(fx.situation.loop).toBe(absPosInt)
fx.stop().animate()
loops = true
absPos = 2.57
absPosInt = Math.floor(absPos)
absPosFrac = absPos - absPosInt
fx.absPos = absPos
fx.loop(loops).step(true)
expect(fx.pos).toBe(absPosFrac)
expect(fx.situation.loop).toBe(absPosInt)
fx.stop().animate()
// With the reverse flag, the position is reversed at each odd loop
loops = 412
absPos = 6.14
absPosInt = Math.floor(absPos)
absPosFrac = absPos - absPosInt
fx.absPos = absPos
fx.loop(loops, true).step(true)
expect(fx.pos).toBe(absPosFrac)
expect(fx.situation.loop).toBe(absPosInt)
expect(fx.situation.reversed).toBe(false)
fx.stop().animate()
loops = true
absPos = 5.12
absPosInt = Math.floor(absPos)
absPosFrac = absPos - absPosInt
fx.absPos = absPos
fx.loop(loops, true).step(true)
expect(fx.pos).toBe(1-absPosFrac) // Odd loop, so it is reversed
expect(fx.situation.loop).toBe(absPosInt)
expect(fx.situation.reversed).toBe(true)
fx.stop().animate()
// When the animation is set to run backward, it is the opposite, the position is reversed at each even loop
loops = 14
absPos = 8.46
absPosInt = Math.floor(absPos)
absPosFrac = absPos - absPosInt
fx.absPos = absPos
fx.reverse(true).loop(loops, true).step(true)
expect(fx.pos).toBe(1-absPosFrac) // Even loop, so it is reversed
expect(fx.situation.loop).toBe(absPosInt)
expect(fx.situation.reversed).toBe(true)
fx.stop().animate()
loops = true
absPos = 3.12
absPosInt = Math.floor(absPos)
absPosFrac = absPos - absPosInt
fx.absPos = absPos
fx.reverse(true).loop(loops, true).step(true)
expect(fx.pos).toBe(absPosFrac)
expect(fx.situation.loop).toBe(absPosInt)
expect(fx.situation.reversed).toBe(false)
})
it('should, when the absolute position is above or equal to the the maximum number of loops, set the position to its end value and end the animation', function() {
var absPos, loops
// Without the reverse flag, the end value of position is 1
loops = 6
absPos = 13.52
fx.absPos = absPos
fx.loop(loops).step(true)
expect(fx.pos).toBe(1)
expect(fx.situation).toBeNull()
fx.animate() // Recreate an animation since the other one was ended
loops = false
absPos = 146.22
fx.absPos = absPos
fx.loop(loops).step(true)
expect(fx.pos).toBe(1)
expect(fx.situation).toBeNull()
fx.animate() // Recreate an animation since the other one was ended
// With the reverse flag, the end value of position is 0 when loops is even and 1 when loops is an odd number or false
loops = 6
absPos = 6
fx.absPos = absPos
fx.loop(loops, true).step(true)
expect(fx.pos).toBe(0) // Even loops
expect(fx.situation).toBeNull()
fx.animate() // Recreate an animation since the other one was ended
loops = false
absPos = 4.47
fx.absPos = absPos
fx.loop(loops, true).step(true)
expect(fx.pos).toBe(1) // 1 since loops is false
expect(fx.situation).toBeNull()
fx.animate() // Recreate an animation since the other one was ended
// When the animation is set to run backward, it is the opposite, the end value of position is 1 when loops is even and 0 when loops is an odd number or false
loops = 8
absPos = 12.65
fx.absPos = absPos
fx.reverse(true).loop(loops, true).step(true)
expect(fx.pos).toBe(1) // Even loops
expect(fx.situation).toBeNull()
fx.animate() // Recreate an animation since the other one was ended
loops = 11
absPos = 12.41
fx.absPos = absPos
fx.reverse(true).loop(loops, true).step(true)
expect(fx.pos).toBe(0) // Odd loops
expect(fx.situation).toBeNull()
})
it('should set the position to its start value when the absolute position is below 0', function() {
var absPos
// When the animation is not set to run backward the start value is 0
absPos = -2.27
fx.loop(7)
fx.situation.loop = 3
fx.absPos = absPos
fx.step(true)
expect(fx.pos).toBe(0)
expect(fx.absPos).toBe(absPos)
expect(fx.situation.loop).toBe(0)
fx.stop().animate()
// When the animation is set to run backward the start value is 1
absPos = -4.12
fx.absPos = absPos
fx.reverse(true).step(true)
expect(fx.pos).toBe(1)
expect(fx.absPos).toBe(absPos)
})
it('should, when looping with the reverse flag, toggle reversed only when the difference between the new value of loop counter and its old value is odd', function() {
// The new value of the loop counter is the integer part of absPos
fx.loop(9, true)
expect(fx.situation.loop).toBe(0)
expect(fx.pos).toBe(0)
expect(fx.situation.reversed).toBe(false)
fx.absPos = 3
fx.step(true)
expect(fx.situation.reversed).toBe(true) // (3-0) is odd
fx.absPos = 1
fx.step(true)
expect(fx.situation.reversed).toBe(true) // (1-3) is even
fx.absPos = 6
fx.step(true)
expect(fx.situation.reversed).toBe(false) // (6-1) is odd
fx.absPos = 9
fx.step(true)
expect(fx.situation).toBeNull()
expect(fx.pos).toBe(1) // It should end not reversed, which mean the position is expected to be 1
// ((9-1)-6) is even, the -1 is because we do not want reversed to be toggled after the last loop
})
it('should not throw an error when stop is called in a during callback', function () {
fx.move(100,100).start()
fx.during(function () {this.stop()})
expect(fx.step.bind(fx)).not.toThrow()
})
it('should not throw an error when finish is called in a during callback', function () {
fx.move(100,100).start()
fx.during(function () {this.finish()})
expect(fx.step.bind(fx)).not.toThrow()
})
})
})
it('animates the x/y-attr', function() {
var called = false
fx.move(200,200).after(function(){
expect(rect.x()).toBe(200)
expect(rect.y()).toBe(200)
called = true
})
jasmine.clock().tick(250)
fx.step()
expect(rect.x()).toBeGreaterThan(100)
expect(rect.y()).toBeGreaterThan(100)
jasmine.clock().tick(250)
fx.step()
expect(called).toBe(true)
})
it('animates matrix', function() {
var ctm, called = false
fx.transform({a:0.8, b:0.4, c:-0.15, d:0.7, e: 90.3, f: 27.07}).after(function(){
var ctm = rect.ctm()
expect(ctm.a).toBeCloseTo(0.8)
expect(ctm.b).toBeCloseTo(0.4)
expect(ctm.c).toBeCloseTo(-0.15)
expect(ctm.d).toBeCloseTo(0.7)
expect(ctm.e).toBeCloseTo(90.3)
expect(ctm.f).toBeCloseTo(27.07)
called = true
})
jasmine.clock().tick(250)
fx.step()
ctm = rect.ctm()
expect(ctm.a).toBeLessThan(1)
expect(ctm.b).toBeGreaterThan(0)
expect(ctm.c).toBeLessThan(0)
expect(ctm.d).toBeGreaterThan(0)
expect(ctm.e).toBeGreaterThan(0)
expect(ctm.f).toBeGreaterThan(0)
jasmine.clock().tick(250)
fx.step()
expect(called).toBe(true)
})
it('animate a scale transform using the passed center point when there is already a transform in place', function(){
var ctm
// When no ceter point is passed to the method scale, it use the center of the element as the center point
rect.scale(2) // The transform in place
fx.scale(0.5)
jasmine.clock().tick(500) // Have the animation reach its end
fx.step()
ctm = rect.ctm()
expect(ctm.a).toBe(0.5)
expect(ctm.b).toBe(0)
expect(ctm.c).toBe(0)
expect(ctm.d).toBe(0.5)
expect(ctm.e).toBe(75)
expect(ctm.f).toBe(75)
})
it('animate a flip(x) transform', function() {
var ctm
fx.transform({flip: 'x'}).start()
jasmine.clock().tick(125) // Have the animation be 1/4 of the way (not halfway as usual because of a bug in the node method getCTM on Firefox)
fx.step()
ctm = rect.ctm()
expect(ctm.a).toBe(0.5)
expect(ctm.b).toBe(0)
expect(ctm.c).toBe(0)
expect(ctm.d).toBe(1)
expect(ctm.e).toBe(75)
expect(ctm.f).toBe(0)
jasmine.clock().tick(475) // Have the animation reach its end
fx.step()
ctm = rect.ctm()
expect(ctm.a).toBe(-1)
expect(ctm.b).toBe(0)
expect(ctm.c).toBe(0)
expect(ctm.d).toBe(1)
expect(ctm.e).toBe(300)
expect(ctm.f).toBe(0)
})
it('animate a flip(x) transform with an offset', function() {
var ctm
fx.transform({flip: 'x', offset: 20}).start()
jasmine.clock().tick(125) // Have the animation be 1/4 of the way (not halfway as usual because of a bug in the node method getCTM on Firefox)
fx.step()
ctm = rect.ctm()
expect(ctm.a).toBe(0.5)
expect(ctm.b).toBe(0)
expect(ctm.c).toBe(0)
expect(ctm.d).toBe(1)
expect(ctm.e).toBe(10)
expect(ctm.f).toBe(0)
jasmine.clock().tick(475) // Have the animation reach its end
fx.step()
ctm = rect.ctm()
expect(ctm.a).toBe(-1)
expect(ctm.b).toBe(0)
expect(ctm.c).toBe(0)
expect(ctm.d).toBe(1)
expect(ctm.e).toBe(40)
expect(ctm.f).toBe(0)
})
it('animate a flip(y) transform', function() {
var ctm
fx.transform({flip: 'y'}).start()
jasmine.clock().tick(125) // Have the animation be 1/4 of the way (not halfway as usual because of a bug in the node method getCTM on Firefox)
fx.step()
ctm = rect.ctm()
expect(ctm.a).toBe(1)
expect(ctm.b).toBe(0)
expect(ctm.c).toBe(0)
expect(ctm.d).toBe(0.5)
expect(ctm.e).toBe(0)
expect(ctm.f).toBe(75)
jasmine.clock().tick(475) // Have the animation reach its end
fx.step()
ctm = rect.ctm()
expect(ctm.a).toBe(1)
expect(ctm.b).toBe(0)
expect(ctm.c).toBe(0)
expect(ctm.d).toBe(-1)
expect(ctm.e).toBe(0)
expect(ctm.f).toBe(300)
})
it('animate a flip(y) transform with an offset', function() {
var ctm
fx.transform({flip: 'y', offset: 20}).start()
jasmine.clock().tick(125) // Have the animation be 1/4 of the way (not halfway as usual because of a bug in the node method getCTM on Firefox)
fx.step()
ctm = rect.ctm()
expect(ctm.a).toBe(1)
expect(ctm.b).toBe(0)
expect(ctm.c).toBe(0)
expect(ctm.d).toBe(0.5)
expect(ctm.e).toBe(0)
expect(ctm.f).toBe(10)
jasmine.clock().tick(475) // Have the animation reach its end
fx.step()
ctm = rect.ctm()
expect(ctm.a).toBe(1)
expect(ctm.b).toBe(0)
expect(ctm.c).toBe(0)
expect(ctm.d).toBe(-1)
expect(ctm.e).toBe(0)
expect(ctm.f).toBe(40)
})
it('animate a flip() transform', function() {
var ctm
fx.transform({flip: 'both'}).start()
jasmine.clock().tick(125) // Have the animation be 1/4 of the way (not halfway as usual because of a bug in the node method getCTM on Firefox)
fx.step()
ctm = rect.ctm()
expect(ctm.a).toBe(0.5)
expect(ctm.b).toBe(0)
expect(ctm.c).toBe(0)
expect(ctm.d).toBe(0.5)
expect(ctm.e).toBe(75)
expect(ctm.f).toBe(75)
jasmine.clock().tick(475) // Have the animation reach its end
fx.step()
ctm = rect.ctm()
expect(ctm.a).toBe(-1)
expect(ctm.b).toBe(0)
expect(ctm.c).toBe(0)
expect(ctm.d).toBe(-1)
expect(ctm.e).toBe(300)
expect(ctm.f).toBe(300)
})
it('animate a flip() transform with an offset', function() {
var ctm
fx.transform({flip: 'both', offset: 20}).start()
jasmine.clock().tick(125) // Have the animation be 1/4 of the way (not halfway as usual because of a bug in the node method getCTM on Firefox)
fx.step()
ctm = rect.ctm()
expect(ctm.a).toBe(0.5)
expect(ctm.b).toBe(0)
expect(ctm.c).toBe(0)
expect(ctm.d).toBe(0.5)
expect(ctm.e).toBe(10)
expect(ctm.f).toBe(10)
jasmine.clock().tick(475) // Have the animation reach its end
fx.step()
ctm = rect.ctm()
expect(ctm.a).toBe(-1)
expect(ctm.b).toBe(0)
expect(ctm.c).toBe(0)
expect(ctm.d).toBe(-1)
expect(ctm.e).toBe(40)
expect(ctm.f).toBe(40)
})
it('animate relative matrix transform', function(){
var ctm
fx.transform(new SVG.Matrix().scale(2,0,0), true)
jasmine.clock().tick(250) // Have the animation be half way
fx.step()
ctm = rect.ctm()
expect(ctm.a).toBe(1.5)
expect(ctm.b).toBe(0)
expect(ctm.c).toBe(0)
expect(ctm.d).toBe(1.5)
expect(ctm.e).toBe(0)
expect(ctm.f).toBe(0)
jasmine.clock().tick(250) // Have the animation reach its end
fx.step()
ctm = rect.ctm()
expect(ctm.a).toBe(2)
expect(ctm.b).toBe(0)
expect(ctm.c).toBe(0)
expect(ctm.d).toBe(2)
expect(ctm.e).toBe(0)
expect(ctm.f).toBe(0)
})
describe('when animating plots', function() {
it('should allow plot animations to be chained', function() {
var pathString1 = 'M10 80 C 40 10, 65 10, 95 80 S 150 150, 180 80'
, pathString2 = 'M10 80 C 40 150, 65 150, 95 80 S 150 10, 180 80'
, path = draw.path(pathString1)
, morph
fx = path.animate(1000).plot(pathString2).animate(1000).plot(pathString1)
morph = new SVG.PathArray(pathString1).morph(pathString2)
fx.start()
expect(path.array()).toEqual(morph.at(0))
jasmine.clock().tick(500) // Have the first animation be half way
fx.step()
expect(path.array()).toEqual(morph.at(0.5))
jasmine.clock().tick(500) // Have the first animation reach its end
fx.step()
expect(path.array()).toEqual(morph.at(1))
morph = new SVG.PathArray(pathString2).morph(pathString1)
expect(path.array()).toEqual(morph.at(0))
jasmine.clock().tick(500) // Have the second animation be half way
fx.step()
expect(path.array()).toEqual(morph.at(0.5))
jasmine.clock().tick(500) // Have the second animation reach its end
fx.step()
expect(path.array()).toEqual(morph.at(1))
})
it('should allow plot to be called on a polyline', function() {
var startValue = [[0,0], [100,50], [50,100], [150,50], [200,50]]
, endValue = [[0,0], [100,50], [50,100], [150,50], [200,50], [250,100], [300,50], [350,50]]
, morph = new SVG.PointArray(startValue).morph(endValue)
, polyline = draw.polyline(startValue)
fx = polyline.animate(3000).plot(endValue)
fx.start()
expect(polyline.array()).toEqual(morph.at(0))
jasmine.clock().tick(1500) // Have the animation be half way
fx.step()
expect(polyline.array()).toEqual(morph.at(0.5))
jasmine.clock().tick(1500) // Have the animation reach its end
fx.step()
expect(polyline.array()).toEqual(morph.at(1))
})
it('should allow plot to be called on a polygon', function() {
var startValue = [[0,0], [100,50], [50,100], [150,50], [200,50]]
, endValue = [[0,0], [100,50], [50,100], [150,50], [200,50], [250,100], [300,50], [350,50]]
, morph = new SVG.PointArray(startValue).morph(endValue)
, polygon = draw.polygon(startValue)
fx = polygon.animate(3000).plot(endValue)
fx.start()
expect(polygon.array()).toEqual(morph.at(0))
jasmine.clock().tick(1500) // Have the animation be half way
fx.step()
expect(polygon.array()).toEqual(morph.at(0.5))
jasmine.clock().tick(1500) // Have the animation reach its end
fx.step()
expect(polygon.array()).toEqual(morph.at(1))
})
it('should allow plot to be called on a path', function() {
var startValue = new SVG.PathArray('M10 80 C 40 10, 65 10, 95 80 S 150 150, 180 80')
, endValue = new SVG.PathArray('M10 80 C 40 150, 65 150, 95 80 S 150 10, 180 80')
, morph = new SVG.PathArray(startValue).morph(endValue)
, path = draw.path(startValue)
fx = path.animate(2000).plot(endValue)
fx.start()
expect(path.array()).toEqual(morph.at(0))
jasmine.clock().tick(1000) // Have the animation be half way
fx.step()
expect(path.array()).toEqual(morph.at(0.5))
jasmine.clock().tick(1000) // Have the animation reach its end
fx.step()
expect(path.array()).toEqual(morph.at(1))
})
it('should allow plot to be called on a textpath', function() {
var startValue = new SVG.PathArray('M10 80 C 40 10, 65 10, 95 80 S 150 150, 180 80')
, endValue = new SVG.PathArray('M10 80 C 40 150, 65 150, 95 80 S 150 10, 180 80')
, morph = new SVG.PathArray(startValue).morph(endValue)
var text = draw.text(function(add) {
add.tspan("We go up and down, then we go down, then up again")
})
fx = text.path(startValue).animate(500).plot(endValue)
fx.start()
expect(text.array()).toEqual(morph.at(0))
jasmine.clock().tick(250) // Have the animation be half way
fx.step()
expect(text.array()).toEqual(morph.at(0.5))
jasmine.clock().tick(250) // Have the animation reach its end
fx.step()
expect(text.array()).toEqual(morph.at(1))
})
it('should allow plot to be called on a line', function() {
var startValue = '0,0 100,150'
, endValue = [[50,30], [120,250]]
, morph = new SVG.PointArray(startValue).morph(endValue)
, line = draw.line(startValue)
fx = line.animate(3000).plot(endValue)
fx.start()
expect(line.array()).toEqual(morph.at(0))
jasmine.clock().tick(1500) // Have the animation be half way
fx.step()
expect(line.array()).toEqual(morph.at(0.5))
jasmine.clock().tick(1500) // Have the animation reach its end
fx.step()
expect(line.array()).toEqual(morph.at(1))
})
it('should allow plot to be called with 4 parameters on a line', function () {
var startPointArray = new SVG.PointArray('0,0 100,150')
, endPointArray = new SVG.PointArray([[50,30], [120,250]])
, morph = new SVG.PointArray(startPointArray).morph(endPointArray)
, a
a = startPointArray.value
var line = draw.line(a[0][0], a[0][1], a[1][0], a[1][1])
a = endPointArray.value
fx = line.animate(3000).plot(a[0][0], a[0][1], a[1][0], a[1][1])
fx.start()
expect(line.array()).toEqual(morph.at(0))
jasmine.clock().tick(1500) // Have the animation be half way
fx.step()
expect(line.array()).toEqual(morph.at(0.5))
jasmine.clock().tick(1500) // Have the animation reach its end
fx.step()
expect(line.array()).toEqual(morph.at(1))
})
})
describe('when animating attributes', function() {
it('should be possible to animate numeric attributes', function () {
var startValue = 0
, endValue = 150
, morph = new SVG.Number(startValue).morph(endValue)
var text = draw.text(function(add) {
add.tspan('We go ')
add.tspan('up').fill('#f09').dy(-40)
add.tspan(', then we go down, then up again').dy(40)
})
var path = 'M 100 200 C 200 100 300 0 400 100 C 500 200 600 300 700 200 C 800 100 900 100 900 100'
text.path(path).font({ size: 42.5, family: 'Verdana' })
text.textPath().attr('startOffset', startValue)
fx = text.textPath().animate(1000).attr('startOffset', endValue)
fx.start()
expect(text.textPath().attr('startOffset')).toBe(morph.at(0).value)
jasmine.clock().tick(500) // Have the animation be half way
fx.step()
expect(text.textPath().attr('startOffset')).toBe(morph.at(0.5).value)
jasmine.clock().tick(500) // Have the animation reach its end
fx.step()
expect(text.textPath().attr('startOffset')).toBe(morph.at(1).value)
})
it('should be possible to animate non-numeric attributes', function () {
var startValue = 'butt'
, endValue = 'round'
, line = draw.line('0,0 100,150').attr('stroke-linecap', startValue)
fx = line.animate(3000).attr('stroke-linecap', endValue)
fx.start()
expect(line.attr('stroke-linecap')).toBe(startValue)
jasmine.clock().tick(1500) // Have the animation be half way
fx.step()
expect(line.attr('stroke-linecap')).toBe(startValue)
jasmine.clock().tick(1500) // Have the animation reach its end
fx.step()
expect(line.attr('stroke-linecap')).toBe(endValue)
})
it('should be possible to animate color attributes by using SVG.Color', function() {
var startValue = 'rgb(42,251,100)'
, endValue = 'rgb(10,80,175)'
, morph = new SVG.Color(startValue).morph(endValue)
rect.attr('fill', startValue)
fx.attr('fill', endValue)
fx.start()
expect(rect.attr('fill')).toBe(morph.at(0).toString())
jasmine.clock().tick(250) // Have the animation be half way
fx.step()
expect(rect.attr('fill')).toBe(morph.at(0.5).toString())
jasmine.clock().tick(250) // Have the animation reach its end
fx.step()
expect(rect.attr('fill')).toBe(morph.at(1).toString())
})
it('should be possible to pass percentage strings to numeric attributes', function () {
var startValue = '0%'
, endValue = '80%'
, morph = new SVG.Number(startValue).morph(endValue)
var text = draw.text(function(add) {
add.tspan('We go ')
add.tspan('up').fill('#f09').dy(-40)
add.tspan(', then we go down, then up again').dy(40)
})
var path = 'M 100 200 C 200 100 300 0 400 100 C 500 200 600 300 700 200 C 800 100 900 100 900 100'
text.path(path).font({ size: 42.5, family: 'Verdana' })
text.textPath().attr('startOffset', startValue)
fx = text.textPath().animate(1000).attr('startOffset', endValue)
fx.start()
expect(text.textPath().attr('startOffset')).toBe(morph.at(0).toString())
jasmine.clock().tick(500) // Have the animation be half way
fx.step()
expect(text.textPath().attr('startOffset')).toBe(morph.at(0.5).toString())
jasmine.clock().tick(500) // Have the animation reach its end
fx.step()
expect(text.textPath().attr('startOffset')).toBe(morph.at(1).toString())
})
it('should allow 0 to be specified without unit', function () {
// This code snippet come from issue #552
var gradient = draw.gradient('linear', function(stop) {
s1 = stop.at(0, '#33235b')
s2 = stop.at(0.5, '#E97639')
s3 = stop.at(1, '#33235b')
})
var r1, r2;
var fill = draw.pattern('300%', '100%', function(add) {
r1 = add.rect('150%', '100%').fill(gradient)
r2 = add.rect('150%', '100%').fill(gradient)
});
fill.attr({patternUnits: 'userSpaceOnUse'})
r1.attr('x', 0).animate('0.5s').attr('x', '150%')
r2.attr('x', '-150%').animate('0.5s').attr('x', 0)
var text = draw.text('Manifesto').move('50%', '50%').fill(fill)
text.font({
size: 70
, anchor: 'middle'
, leading: 1
})
r1.fx.start()
r2.fx.start()
jasmine.clock().tick(250) // Have the animation be half way
r1.fx.step()
r2.fx.step()
expect(r1.attr('x')).toBe('75%')
expect(r2.attr('x')).toBe('-75%')
jasmine.clock().tick(250) // Have the animation reach its end
r1.fx.step()
r2.fx.step()
expect(r1.attr('x')).toBe('150%')
expect(r2.attr('x')).toBe('0%')
})
})
describe('when animating styles', function() {
it('should be possible to animate numeric styles', function () {
var startValue = 0
, endValue = 5
, morph = new SVG.Number(startValue).morph(endValue)
rect.style('stroke-width', startValue)
fx.style('stroke-width', endValue)
fx.start()
expect(rect.style('stroke-width')).toBe(morph.at(0).toString())
jasmine.clock().tick(250) // Have the animation be half way
fx.step()
expect(rect.style('stroke-width')).toBe(morph.at(0.5).toString())
jasmine.clock().tick(250) // Have the animation reach its end
fx.step()
expect(rect.style('stroke-width')).toBe(morph.at(1).toString())
})
it('should be possible to animate non-numeric styles', function () {
var startValue = 'butt'
, endValue = 'round'
, line = draw.line('0,0 100,150').style('stroke-linecap', startValue)
fx = line.animate(3000).style('stroke-linecap', endValue)
fx.start()
expect(line.style('stroke-linecap')).toBe(startValue)
jasmine.clock().tick(1500) // Have the animation be half way
fx.step()
expect(line.style('stroke-linecap')).toBe(startValue)
jasmine.clock().tick(1500) // Have the animation reach its end
fx.step()
expect(line.style('stroke-linecap')).toBe(endValue)
})
it('should be possible to animate color styles by using SVG.Color', function() {
var startValue = '#81DE01'
, endValue = '#B1835D'
, morph = new SVG.Color(startValue).morph(endValue)
rect.style('fill', startValue)
fx.style('fill', endValue)
fx.start()
// When setting a style color, it get saved as a rgb() string even if it was passed as an hex code
// The style rgb string has spaces while the one returned by SVG.Color do not as show bellow
// CSS: rgb(255, 255, 255) SVG.Color: rgb(255,255,255)
// The space in the style rbg string are removed so they can be equal
expect(rect.style('fill').replace(/\s+/g, '')).toBe(morph.at(0).toRgb())
jasmine.clock().tick(250) // Have the animation be half way
fx.step()
expect(rect.style('fill').replace(/ /g, '')).toBe(morph.at(0.5).toRgb())
jasmine.clock().tick(250) // Have the animation reach its end
fx.step()
expect(rect.style('fill').replace(/ /g, '')).toBe(morph.at(1).toRgb())
})
it('should be possible to pass percentage strings to numeric styles', function () {
var startValue = '0%'
, endValue = '5%'
, morph = new SVG.Number(startValue).morph(endValue)
rect.style('stroke-width', startValue)
fx.style('stroke-width', endValue)
fx.start()
expect(rect.style('stroke-width')).toBe(morph.at(0).toString())
jasmine.clock().tick(250) // Have the animation be half way
fx.step()
expect(rect.style('stroke-width')).toBe(morph.at(0.5).toString())
jasmine.clock().tick(250) // Have the animation reach its end
fx.step()
expect(rect.style('stroke-width')).toBe(morph.at(1).toString())
})
it('should allow 0 to be specified without a unit', function () {
var r1 = draw.rect(100,100).move(200,200)
, r2 = draw.rect(100,100).move(400,400)
r1.style('stroke-width', '100%').animate(500).style('stroke-width', 0)
r2.style('stroke-width', 0).animate(500).style('stroke-width', '100%')
r1.fx.start()
r2.fx.start()
expect(r1.style('stroke-width')).toBe('100%')
expect(r2.style('stroke-width')).toBe('0%')
jasmine.clock().tick(250) // Have the animation be half way
r1.fx.step()
r2.fx.step()
expect(r1.style('stroke-width')).toBe('50%')
expect(r2.style('stroke-width')).toBe('50%')
jasmine.clock().tick(250) // Have the animation reach its end
r1.fx.step()
r2.fx.step()
expect(r1.style('stroke-width')).toBe('0%')
expect(r2.style('stroke-width')).toBe('100%')
})
})
describe('add()', function() {
it('adds to animations obj by default', function() {
fx.add('x', new SVG.Number(20))
expect(fx.situation.animations.x.value).toBe(20)
})
it('adds to specified obj', function() {
fx.add('x', new SVG.Number(20), 'animations')
fx.add('x', new SVG.Number(20), 'attrs')
fx.add('x', new SVG.Number(20), 'styles')
expect(fx.situation.animations.x.value).toBe(20)
expect(fx.situation.attrs.x.value).toBe(20)
expect(fx.situation.styles.x.value).toBe(20)
})
})
describe('attr()', function() {
it('should allow an object to be passed', function() {
spyOn(fx, 'attr').and.callThrough()
fx.attr({
x: 20,
y: 20
})
expect(fx.attr).toHaveBeenCalledWith('x', 20)
expect(fx.attr).toHaveBeenCalledWith('y', 20)
})
it('should call add() with attrs as method', function() {
spyOn(fx, 'add')
fx.attr('x', 20)
expect(fx.add).toHaveBeenCalledWith('x', 20, 'attrs')
})
})
describe('style()', function() {
it('should allow an object to be passed', function() {
spyOn(fx, 'style').and.callThrough()
fx.style({
x: 20,
y: 20
})
expect(fx.style).toHaveBeenCalledWith('x', 20)
expect(fx.style).toHaveBeenCalledWith('y', 20)
})
it('should call add() with styles as method', function() {
spyOn(fx, 'add')
fx.style('x', 20)
expect(fx.add).toHaveBeenCalledWith('x', 20, 'styles')
})
})
describe('x() / y()', function() {
it('should add an entry to the animations obj', function() {
spyOn(fx, 'add')
fx.x(20)
fx.y(20)
expect(fx.add).toHaveBeenCalledWith('x', jasmine.objectContaining({value:20}))
expect(fx.add).toHaveBeenCalledWith('y', jasmine.objectContaining({value:20}))
})
it('allows relative move with relative flag set', function() {
spyOn(fx, 'add')
fx.x(20, true)
fx.y(20, true)
expect(fx.add).toHaveBeenCalledWith('x', jasmine.objectContaining({value:20, relative:true }))
expect(fx.add).toHaveBeenCalledWith('y', jasmine.objectContaining({value:20, relative:true }))
})
it('redirects to transform when target is a group', function() {
var group = draw.group()
, fx = group.animate(500)
spyOn(fx, 'transform')
fx.x(20)
fx.y(20)
expect(fx.transform).toHaveBeenCalledWith({x: 20}, undefined)
expect(fx.transform).toHaveBeenCalledWith({y: 20}, undefined)
})
it('redirects to transform when target is a group with relative flag set', function() {
var group = draw.group()
, fx = group.animate(500)
spyOn(fx, 'transform')
fx.x(20, true)
fx.y(20, true)
expect(fx.transform).toHaveBeenCalledWith({x: 20}, true)
expect(fx.transform).toHaveBeenCalledWith({y: 20}, true)
})
})
describe('cx() / cy()', function() {
it('should call add with method and argument', function() {
spyOn(fx, 'add')
fx.cx(20)
fx.cy(20)
expect(fx.add).toHaveBeenCalledWith('cx', jasmine.objectContaining({value:20}))
expect(fx.add).toHaveBeenCalledWith('cy', jasmine.objectContaining({value:20}))
})
})
describe('move()', function() {
it('should redirect call to x() and y()', function() {
spyOn(fx, 'x').and.callThrough()
spyOn(fx, 'y').and.callThrough()
fx.move(20, 20)
expect(fx.x).toHaveBeenCalledWith(20)
expect(fx.y).toHaveBeenCalledWith(20)
})
})
describe('center()', function() {
it('should redirect call to cx() and cy()', function() {
spyOn(fx, 'cx').and.callThrough()
spyOn(fx, 'cy').and.callThrough()
fx.center(20, 20)
expect(fx.cx).toHaveBeenCalledWith(20)
expect(fx.cy).toHaveBeenCalledWith(20)
})
})
describe('size()', function() {
it('should set font-size with attr() when called on a text', function() {
var text = draw.text('Hello World')
, fx = text.animate(500)
spyOn(fx, 'attr')
fx.size(20)
expect(fx.attr).toHaveBeenCalledWith('font-size', 20)
})
it('should set width and height with add()', function() {
spyOn(fx, 'add').and.callThrough()
fx.size(20, 20)
expect(fx.add).toHaveBeenCalledWith('width', jasmine.objectContaining({value:20}))
expect(fx.add).toHaveBeenCalledWith('height', jasmine.objectContaining({value:20}))
})
it('should calculate proportional size when only height or width is given', function() {
spyOn(fx, 'add').and.callThrough()
fx.size(40, null)
fx.size(null, 60)
expect(fx.add).toHaveBeenCalledWith('width', jasmine.objectContaining({value:40}))
expect(fx.add).toHaveBeenCalledWith('height', jasmine.objectContaining({value:40}))
expect(fx.add).toHaveBeenCalledWith('width', jasmine.objectContaining({value:60}))
expect(fx.add).toHaveBeenCalledWith('height', jasmine.objectContaining({value:60}))
})
})
describe('plot()', function() {
it('should call add with plot as method', function() {
var polyline = draw.polyline('10 10 20 20 30 10 50 20')
, fx = polyline.animate(500)
spyOn(fx, 'add')
fx.plot('5 5 30 29 40 19 12 30')
expect(fx.add).toHaveBeenCalledWith('plot', '5 5 30 29 40 19 12 30')
})
it('also accept parameter list', function() {
var line = draw.line('10 10 20 20')
, fx = line.animate(500)
spyOn(fx, 'add')
fx.plot(5, 5, 10, 10)
expect(fx.add).toHaveBeenCalledWith('plot', [5, 5, 10, 10])
})
})
describe('leading()', function() {
it('should call add with method and argument', function() {
var text = draw.text('Hello World')
, fx = text.animate(500)
spyOn(fx, 'add')
fx.leading(3)
expect(fx.add).toHaveBeenCalledWith('leading', jasmine.objectContaining({value:3}))
})
it('does nothiing when not called on text', function() {
spyOn(fx, 'add')
fx.leading(3)
expect(fx.add).not.toHaveBeenCalled()
})
})
describe('viewbox()', function() {
it('should call add with method and argument', function() {
var nested = draw.nested()
, fx = nested.animate(500)
spyOn(fx, 'add')
fx.viewbox(1,2,3,4)
expect(fx.add).toHaveBeenCalledWith('viewbox', jasmine.objectContaining({x:1, y:2, width:3, height:4}))
})
it('does nothing when not called on SVG.Container', function() {
spyOn(fx, 'add')
fx.viewbox(1,2,3,4)
expect(fx.add).not.toHaveBeenCalled()
})
})
describe('update()', function() {
it('should convert call with 3 arguments to call with obj', function() {
var stop = new SVG.Stop()
, fx = stop.animate()
spyOn(fx, 'update').and.callThrough()
fx.update(1,'#ccc',0.5)
expect(fx.update).toHaveBeenCalledWith({offset: 1, color: '#ccc', opacity: 0.5})
})
it('calls add with method argument and attrs as type', function() {
var stop = new SVG.Stop()
, fx = stop.animate()
spyOn(fx, 'add')
fx.update({offset: 1, color: '#ccc', opacity: 0.5})
expect(fx.add).toHaveBeenCalledWith('stop-opacity', 0.5, 'attrs')
expect(fx.add).toHaveBeenCalledWith('stop-color', '#ccc', 'attrs')
expect(fx.add).toHaveBeenCalledWith('offset', 1, 'attrs')
})
it('does nothing when not called on SVG.Stop', function() {
spyOn(fx, 'add')
fx.update({offset: 1, color: '#ccc', opacity: 0.5})
expect(fx.add).not.toHaveBeenCalled()
})
})
describe('transform()', function() {
it('returns itself when no valid transformation was found', function() {
expect(fx.transform({})).toBe(fx)
})
it('gets the current transforms', function() {
expect(fx.transform()).toEqual(new SVG.Matrix(rect).extract())
})
it('gets a certain transformation if used with an argument', function() {
expect(fx.transform('x')).toEqual(0)
})
it('adds an entry to transforms when matrix given', function() {
var matrix = new SVG.Matrix(1,2,3,4,5,6)
fx.transform(matrix)
expect(fx.situation.transforms[0]).toEqual(jasmine.objectContaining(matrix))
})
it('sets relative flag when given', function() {
var matrix = new SVG.Matrix(1,2,3,4,5,6)
fx.transform(matrix, true)
expect(fx.situation.transforms[0]).toEqual(jasmine.objectContaining(matrix))
expect(fx.situation.transforms[0].relative).toBe(true)
})
it('adds an entry to transforms when rotation given', function() {
fx.transform({rotation: 30, cx:0, cy:0})
expect(fx.situation.transforms[0]).toEqual(jasmine.objectContaining(new SVG.Rotate(30, 0, 0)))
})
it('adds an entry to transforms when scale given', function() {
fx.transform({scale: 2, cx:0, cy:0})
expect(fx.situation.transforms[0]).toEqual(jasmine.objectContaining(new SVG.Scale(2, 2, 0, 0)))
})
it('adds an entry to transforms when scaleX given', function() {
fx.transform({scaleX: 2, cx:0, cy:0})
expect(fx.situation.transforms[0]).toEqual(jasmine.objectContaining(new SVG.Scale(2, 1, 0, 0)))
})
it('adds an entry to transforms when scaleY given', function() {
fx.transform({scaleY: 2, cx:0, cy:0})
expect(fx.situation.transforms[0]).toEqual(jasmine.objectContaining(new SVG.Scale(1, 2, 0, 0)))
})
it('adds an entry to transforms when skewX given', function() {
fx.transform({skewX: 2, cx:0, cy:0})
expect(fx.situation.transforms[0]).toEqual(jasmine.objectContaining(new SVG.Skew(2, 0, 0, 0)))
})
it('adds an entry to transforms when skewY given', function() {
fx.transform({skewY: 2, cx:0, cy:0})
expect(fx.situation.transforms[0]).toEqual(jasmine.objectContaining(new SVG.Skew(0, 2, 0, 0)))
})
it('adds an entry to transforms when flip x given', function() {
fx.transform({flip: 'x'})
expect(fx.situation.transforms[0]).toEqual(jasmine.objectContaining((new SVG.Matrix()).flip('x', 150)))
})
it('adds an entry to transforms when flip x with offset given', function() {
fx.transform({flip: 'x', offset: 100})
expect(fx.situation.transforms[0]).toEqual(jasmine.objectContaining((new SVG.Matrix()).flip('x', 100)))
})
it('adds an entry to transforms when flip y given', function() {
fx.transform({flip: 'y'})
expect(fx.situation.transforms[0]).toEqual(jasmine.objectContaining((new SVG.Matrix()).flip('y', 150)))
})
it('adds an entry to transforms when x given', function() {
fx.transform({x:20})
expect(fx.situation.transforms[0]).toEqual(jasmine.objectContaining(new SVG.Translate(20, undefined)))
})
it('adds an entry to transforms when y given', function() {
fx.transform({y:20})
expect(fx.situation.transforms[0]).toEqual(jasmine.objectContaining(new SVG.Translate(undefined, 20)))
})
})
/* shortcuts for animation */
describe('animate()', function() {
it('creates a new fx instance on the element', function() {
var rect = draw.rect(100,100)
rect.animate(100)
expect(rect.fx instanceof SVG.FX).toBeTruthy()
})
it('redirects the call to fx.animate()', function() {
spyOn(fx, 'animate')
rect.animate()
expect(fx.animate).toHaveBeenCalled()
})
})
describe('delay()', function() {
it('creates a new fx instance on the element', function() {
var rect = draw.rect(100,100)
rect.delay(100)
expect(rect.fx instanceof SVG.FX).toBeTruthy()
})
it('redirects the call to fx.delay()', function() {
spyOn(fx, 'delay')
rect.delay(5)
expect(fx.delay).toHaveBeenCalled()
})
})
describe('stop()', function() {
it('redirects the call to fx.stop()', function() {
spyOn(fx, 'stop')
rect.stop()
expect(fx.stop).toHaveBeenCalled()
})
})
describe('finish()', function() {
it('redirects the call to fx.finish()', function() {
spyOn(fx, 'finish')
rect.finish()
expect(fx.finish).toHaveBeenCalled()
})
})
describe('pause()', function() {
it('redirects the call to fx.pause()', function() {
spyOn(fx, 'pause')
rect.pause()
expect(fx.pause).toHaveBeenCalled()
})
})
describe('play()', function() {
it('redirects the call to fx.play()', function() {
spyOn(fx, 'play')
rect.play()
expect(fx.play).toHaveBeenCalled()
})
})
describe('speed()', function() {
it('redirects the call to fx.speed() as getter', function() {
spyOn(fx, 'speed')
rect.speed()
expect(fx.speed).toHaveBeenCalled()
})
it('redirects the call to fx.speed() as setter', function() {
spyOn(fx, 'speed').and.callThrough()
expect(rect.speed(5)).toBe(rect)
expect(fx.speed).toHaveBeenCalled()
})
})
})
describe('SVG.MorphObj', function() {
it('accepts color strings and converts them to SVG.Color', function() {
var obj = new SVG.MorphObj('#000', '#fff')
expect(obj instanceof SVG.Color).toBeTruthy()
obj = new SVG.MorphObj('rgb(0,0,0)', 'rgb(255,255,255)')
expect(obj instanceof SVG.Color).toBeTruthy()
})
it('accepts numbers and converts them to SVG.Number', function() {
var obj = new SVG.MorphObj('0', '10')
expect(obj instanceof SVG.Number).toBeTruthy()
var obj = new SVG.MorphObj(0, 10)
expect(obj instanceof SVG.Number).toBeTruthy()
})
it('accepts any other values', function() {
var obj = new SVG.MorphObj('Hello', 'World')
expect(obj.value).toBe('Hello')
expect(obj.destination).toBe('World')
})
it('morphes unmorphable objects with plain morphing', function() {
var obj = new SVG.MorphObj('Hello', 'World')
expect(obj.at(0,0)).toBe('Hello')
expect(obj.at(0.5,0.5)).toBe('Hello')
expect(obj.at(1,1)).toBe('World')
})
it('converts to its value when casted', function() {
var obj = new SVG.MorphObj('Hello', 'World')
expect(obj.valueOf()).toBe('Hello')
expect(obj + 'World').toBe('HelloWorld')
})
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 | 2 | describe('Gradient', function() {
var rect, gradient
beforeEach(function() {
rect = draw.rect(100,100)
gradient = draw.gradient('linear', function(stop) {
stop.at({ offset: 0, color: '#333', opacity: 1 })
stop.at({ offset: 1, color: '#fff', opacity: 1 })
})
radial = draw.gradient('radial', function(stop) {
stop.at({ offset: 0, color: '#333', opacity: 1 })
stop.at({ offset: 1, color: '#fff', opacity: 1 })
})
})
afterEach(function() {
rect.remove()
gradient.remove()
})
it('is an instance of SVG.Gradient', function() {
expect(gradient instanceof SVG.Gradient).toBe(true)
})
it('allows creation of a new gradient without block', function() {
gradient = draw.gradient('linear')
expect(gradient.children().length).toBe(0)
})
describe('fill()', function() {
it('returns the id of the gradient wrapped in url()', function() {
expect(gradient.fill()).toBe('url(#' + gradient.attr('id') + ')')
})
})
describe('from()', function() {
it('sets fx and fy attribute for radial gradients', function() {
radial.from(7, 10)
expect(radial.attr('fx')).toBe(7)
expect(radial.attr('fy')).toBe(10)
})
it('sets x1 and y1 attribute for linear gradients', function() {
gradient.from(7, 10)
expect(gradient.attr('x1')).toBe(7)
expect(gradient.attr('y1')).toBe(10)
})
})
describe('to()', function() {
it('sets cx and cy attribute for radial gradients', function() {
radial.to(75, 105)
expect(radial.attr('cx')).toBe(75)
expect(radial.attr('cy')).toBe(105)
})
it('sets x2 and y2 attribute for linear gradients', function() {
gradient.to(75, 105)
expect(gradient.attr('x2')).toBe(75)
expect(gradient.attr('y2')).toBe(105)
})
})
describe('attr()', function() {
it('will catch transform attribues and convert them to gradientTransform', function() {
expect(gradient.translate(100,100).attr('gradientTransform')).toBe('matrix(1,0,0,1,100,100)')
})
})
describe('toString()', function() {
it('returns the id of the gradient wrapped in url()', function() {
expect(gradient + '').toBe('url(#' + gradient.attr('id') + ')')
})
it('is called when instance is passed as an attribute value', function() {
rect.attr('fill', gradient)
expect(rect.attr('fill')).toBe('url(#' + gradient.attr('id') + ')')
})
})
describe('input values', function() {
var s1, s2
it('accepts floats', function() {
gradient = draw.gradient('linear', function(stop) {
s1 = stop.at({ offset: 0.12, color: '#333', opacity: 1 })
s2 = stop.at({ offset: 0.93, color: '#fff', opacity: 1 })
})
expect(s1.attr('offset')).toBe(0.12)
expect(s2.attr('offset')).toBe(0.93)
})
it('accepts string floats', function() {
gradient = draw.gradient('linear', function(stop) {
s1 = stop.at({ offset: '0.13', color: '#333', opacity: 1 })
s2 = stop.at({ offset: '0.92', color: '#fff', opacity: 1 })
})
expect(s1.attr('offset')).toBe(0.13)
expect(s2.attr('offset')).toBe(0.92)
})
it('accept percentages', function() {
gradient = draw.gradient('linear', function(stop) {
s1 = stop.at({ offset: '14%', color: '#333', opacity: 1 })
s2 = stop.at({ offset: '91%', color: '#fff', opacity: 1 })
})
expect(s1.attr('offset')).toBe('14%')
expect(s2.attr('offset')).toBe('91%')
})
})
describe('update()', function() {
it('removes all existing children first', function() {
gradient = draw.gradient('linear', function(stop) {
s1 = stop.at({ offset: 0.12, color: '#333', opacity: 1 })
s2 = stop.at({ offset: 0.93, color: '#fff', opacity: 1 })
})
expect(gradient.children().length).toBe(2)
gradient.update(function(stop) {
s1 = stop.at({ offset: 0.33, color: '#666', opacity: 1 })
s2 = stop.at({ offset: 1, color: '#000', opacity: 1 })
})
expect(gradient.children().length).toBe(2)
})
it('accepts multiple aruments on fixed positions', function() {
gradient = draw.gradient('linear', function(stop) {
s1 = stop.at(0.11, '#333')
s2 = stop.at(0.94, '#fff', 0.5)
})
expect(gradient.children().length).toBe(2)
expect(s1.attr('offset')).toBe(0.11)
expect(s1.attr('stop-color')).toBe('#333333')
expect(s2.attr('offset')).toBe(0.94)
expect(s2.attr('stop-color')).toBe('#ffffff')
expect(s2.attr('stop-opacity')).toBe(0.5)
})
})
describe('get()', function() {
it('returns the stop at a given index', function() {
gradient = draw.gradient('linear', function(stop) {
s1 = stop.at({ offset: 0.12, color: '#333', opacity: 1 })
s2 = stop.at({ offset: 0.93, color: '#fff', opacity: 1 })
})
expect(gradient.get(0)).toBe(s1)
expect(gradient.get(1)).toBe(s2)
expect(gradient.get(2)).toBeNull()
})
})
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 | 2 | describe('Group', function() {
var group
beforeEach(function() {
group = draw.group().move(50, 50)
group.rect(100,100)
})
afterEach(function() {
draw.clear()
})
describe('x()', function() {
it('returns the value of x without an argument', function() {
expect(group.x()).toBe(50)
})
it('sets the value of x with the first argument', function() {
group.x(123)
var box = group.gbox()
expect(box.x).toBe(123)
})
it('sets the value of x correctly when called multiple times', function() {
group.x(10).x(100).x(13)
var box = group.gbox()
expect(box.x).toBe(13)
})
it('sets the value of x correctly when the first argument is a string number', function(){
group.x('123')
var box = group.gbox()
expect(box.x).toBe(123)
})
})
describe('y()', function() {
it('returns the value of y without an argument', function() {
expect(group.y()).toBe(50)
})
it('sets the value of y with the first argument', function() {
group.y(345)
var box = group.gbox()
expect(box.y).toBe(345)
})
it('sets the value of y correctly when called multiple times', function() {
group.y(1).y(10).y(15)
var box = group.gbox()
expect(box.y).toBe(15)
})
it('sets the value of y correctly when the first argument is a string number', function(){
group.y('124')
var box = group.gbox()
expect(box.y).toBe(124)
})
})
describe('cx()', function() {
it('returns the value of cx without an argument', function() {
expect(group.cx()).toBe(100)
})
it('sets the value of cx with the first argument', function() {
group.cx(123)
var box = group.gbox()
expect(box.cx).toBe(123)
})
})
describe('cy()', function() {
it('returns the value of cy without an argument', function() {
expect(group.cy()).toBe(100)
})
it('sets the value of cy with the first argument', function() {
group.cy(345)
var box = group.gbox()
expect(box.cy).toBe(345)
})
})
describe('move()', function() {
it('sets the x and y position', function() {
group.move(123,456)
expect(group.node.getAttribute('transform')).toBe('matrix(1,0,0,1,123,456)')
})
})
describe('center()', function() {
it('sets the cx and cy position', function() {
group.center(321,567)
var box = group.gbox()
expect(box.cx).toBe(321)
expect(box.cy).toBe(567)
})
})
describe('dx()', function() {
it('moves the x positon of the element relative to the current position', function() {
group.move(50,60)
group.dx(100)
expect(group.node.getAttribute('transform')).toBe('matrix(1,0,0,1,150,60)')
})
})
describe('dy()', function() {
it('moves the y positon of the element relative to the current position', function() {
group.move(50,60)
group.dy(120)
expect(group.node.getAttribute('transform')).toBe('matrix(1,0,0,1,50,180)')
})
})
describe('dmove()', function() {
it('moves the x and y positon of the element relative to the current position', function() {
group.move(50, 60)
group.dmove(80, 25)
expect(group.node.getAttribute('transform')).toBe('matrix(1,0,0,1,130,85)')
})
})
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 | 2 2 2 1 | // create canavs //var drawing, window = window, document = document, SVG = SVG parserInDoc = false Eif(typeof exports === 'object'){ window = require('svgdom') SVG = require('../../dist/svg.js') document = window.document drawing = document.documentElement imageUrl = 'spec/fixtures/pixel.png' parserInDoc = true function tag(name, attrs, children) { var el = document.createElement(name) for(var i in attrs){ el.setAttribute(i, attrs[i]) } for(var i in children){ if(typeof children[i] == 'string') children[i] = document.createTextNode(children[i]) el.appendChild(children[i]) } return el } // create fixtures in svgdom var el = tag('svg', { height:0, width:0, id:'inlineSVG' },[ tag('defs', {}, [ tag('linearGradient', {}, [ tag('stop', {offset: '5%', 'stop-color': 'green'}), tag('stop', {offset: '95%', 'stop-color': 'gold'}), ]), tag('radialGradient', {}, [ tag('stop', {offset: '5%', 'stop-color': 'green'}), tag('stop', {offset: '95%', 'stop-color': 'gold'}), ]) ]), tag('desc', {}, ['Some description']), tag('path', { id: 'lineAB', d: 'M 100 350 l 150 -300', stroke: 'red', 'stroke-width': '3', fill: 'none' }), tag('path', { id: 'lineBC', d: 'M 250 50 l 150 300', stroke: 'red', 'stroke-width': '3', fill: 'none' }), tag('path', { d: 'M 175 200 l 150 0', stroke: 'green', 'stroke-width': '3', fill: 'none' }), tag('path', { d: 'M 100 350 q 150 -300 300 0', stroke: 'blue', 'stroke-width': '5', fill: 'none' }), tag('g', { stroke: 'black', 'stroke-width': '2', fill: 'black', id: 'pointGroup' },[ tag('circle', { id: 'pointA', cx: '100', cy: '350', r: '3', }), tag('circle', { id: 'pointB', cx: '250', cy: '50', r: '50', }), tag('circle', { id: 'pointC', cx: '400', cy: '350', r: '50', }) ]), tag('g', { 'font-size': '30', font: 'sans-serif', fill: 'black', stroke: 'none', 'text-anchor': 'middle', id: 'labelGroup' },[ tag('text', { x: '100', y: '350', dy: '-30', }, ['A']), tag('text', { x: '250', y: '50', dy: '-10', }, ['B']), tag('text', { x: '400', y: '350', dx: '30', }, ['C']) ]), tag('polygon', {points: '200,10 250,190 160,210'}), tag('polyline', {points: '20,20 40,25 60,40 80,120 120,140 200,180'}) ]) document.appendChild(el) }else{ drawing = document.createElement('div') document.getElementsByTagName('body')[0].appendChild(drawing) imageUrl = 'fixtures/pixel.png' } parserInDoc |= 0 drawing.id = 'drawing' draw = SVG(drawing).size(100,100) parser = parserInDoc ? [SVG.parser.draw.instance] : [] // raw path data svgPath = 'M88.006,61.994c3.203,0,6.216-1.248,8.481-3.514C98.752,56.215,100,53.203,100,50c0-3.204-1.248-6.216-3.513-8.481 c-2.266-2.265-5.278-3.513-8.481-3.513c-2.687,0-5.237,0.877-7.327,2.496h-7.746l5.479-5.479 c5.891-0.757,10.457-5.803,10.457-11.896c0-6.614-5.381-11.995-11.994-11.995c-6.093,0-11.14,4.567-11.896,10.457l-5.479,5.479 v-7.747c1.618-2.089,2.495-4.641,2.495-7.327c0-3.204-1.247-6.216-3.513-8.481C56.216,1.248,53.204,0,50,0 c-3.204,0-6.216,1.248-8.481,3.513c-2.265,2.265-3.513,5.277-3.513,8.481c0,2.686,0.877,5.237,2.495,7.327v7.747l-5.479-5.479 c-0.757-5.89-5.803-10.457-11.896-10.457c-6.614,0-11.995,5.381-11.995,11.995c0,6.093,4.567,11.139,10.458,11.896l5.479,5.479 h-7.747c-2.089-1.619-4.641-2.496-7.327-2.496c-3.204,0-6.216,1.248-8.481,3.513C1.248,43.784,0,46.796,0,50 c0,3.203,1.248,6.216,3.513,8.48c2.265,2.266,5.277,3.514,8.481,3.514c2.686,0,5.237-0.877,7.327-2.496h7.747l-5.479,5.479 c-5.891,0.757-10.458,5.804-10.458,11.896c0,6.614,5.381,11.994,11.995,11.994c6.093,0,11.139-4.566,11.896-10.457l5.479-5.479 v7.749c-3.63,4.7-3.291,11.497,1.018,15.806C43.784,98.752,46.796,100,50,100c3.204,0,6.216-1.248,8.481-3.514 c4.309-4.309,4.647-11.105,1.018-15.806v-7.749l5.479,5.479c0.757,5.891,5.804,10.457,11.896,10.457 c6.613,0,11.994-5.38,11.994-11.994c0-6.093-4.566-11.14-10.457-11.896l-5.479-5.479h7.746 C82.769,61.117,85.319,61.994,88.006,61.994z M76.874,68.354c4.705,0,8.52,3.814,8.52,8.521c0,4.705-3.814,8.52-8.52,8.52 s-8.52-3.814-8.52-8.52l-12.33-12.33V81.98c3.327,3.328,3.327,8.723,0,12.049c-3.327,3.328-8.722,3.328-12.049,0 c-3.327-3.326-3.327-8.721,0-12.049V64.544l-12.33,12.33c0,4.705-3.814,8.52-8.52,8.52s-8.52-3.814-8.52-8.52 c0-4.706,3.814-8.521,8.52-8.521l12.33-12.33H18.019c-3.327,3.328-8.722,3.328-12.049,0c-3.327-3.326-3.327-8.721,0-12.048 s8.722-3.327,12.049,0h17.438l-12.33-12.33c-4.706,0-8.52-3.814-8.52-8.52c0-4.706,3.814-8.52,8.52-8.52s8.52,3.814,8.52,8.52 l12.33,12.33V18.019c-3.327-3.327-3.327-8.722,0-12.049s8.722-3.327,12.049,0s3.327,8.722,0,12.049v17.438l12.33-12.33 c0-4.706,3.814-8.52,8.52-8.52s8.52,3.814,8.52,8.52c0,4.705-3.814,8.52-8.52,8.52l-12.33,12.33h17.438 c3.327-3.327,8.722-3.327,12.049,0s3.327,8.722,0,12.048c-3.327,3.328-8.722,3.328-12.049,0H64.544L76.874,68.354z' // image url // lorem ipsum text loremIpsum = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras sodales\n imperdiet auctor. Nunc ultrices lectus at erat dictum pharetra\n elementum ante posuere. Duis turpis risus, blandit nec elementum et,\n posuere eget lacus. Aliquam et risus magna, eu aliquet nibh. Fusce\n consequat mi quis purus varius sagittis euismod urna interdum.\n Curabitur aliquet orci quis felis semper vulputate. Vestibulum ac nisi\n magna, id dictum diam. Proin sed metus vel magna blandit\n sodales. Pellentesque at neque ultricies nunc euismod rutrum ut in\n lorem. Mauris euismod tellus in tellus tempus interdum. Phasellus\n mattis sapien et leo feugiat dictum. Vestibulum at volutpat velit.' beforeEach(function(){ // test for touch device this.isTouchDevice = 'ontouchstart' in document.documentElement }) // strip spaces from result window.stripped = function(string) { string = string.replace(/\s+/g, '') if(string.slice(-1) == ';') string = string.slice(0, -1) return string } // This is needed because of IE11 which uses space as a delimiter in matrix window.matrixStringToArray = function(source){ return source .replace(/matrix\(|\)/, '') .split(SVG.regex.delimiter) .map(parseFloat) } // This is needed because of IE11 creating values like 2.99999 when calculating a transformed box window.roundBox = function(box) { return new SVG.Box( Math.round(box.x), Math.round(box.y), Math.round(box.width), Math.round(box.height) ) } |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | 2 | describe('Hyperlink', function() {
var link
, url = 'http://svgjs.com'
beforeEach(function() {
link = draw.link(url)
link.rect(100,100)
})
afterEach(function() {
draw.clear()
})
it('creates a link', function() {
expect(link.attr('href')).toBe(url)
})
describe('to()', function() {
it('creates xlink:href attribute', function() {
link.to('http://apple.com')
expect(link.attr('href')).toBe('http://apple.com')
})
})
describe('show()', function() {
it('creates xlink:show attribute', function() {
link.show('replace')
expect(link.attr('show')).toBe('replace')
})
})
describe('target()', function() {
it('creates target attribute', function() {
link.target('_blank')
expect(link.attr('target')).toBe('_blank')
})
})
describe('SVG.Element', function() {
var element
beforeEach(function() {
element = draw.rect(100,100)
})
describe('linkTo()', function() {
it('wraps the called element in a link with given url', function() {
element.linkTo(url)
expect(element.parent().attr('href')).toBe(url)
})
it('wraps the called element in a link with given block', function() {
element.linkTo(function(link) {
link.to(url).target('_blank')
})
expect(element.parent().attr('href')).toBe(url)
expect(element.parent().attr('target')).toBe('_blank')
})
})
})
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 | 2 | describe('Image', function() {
var image
beforeEach(function() {
image = draw.image(imageUrl, 100, 100)
})
afterEach(function() {
draw.clear()
})
describe('()', function() {
it('should set width and height automatically if no size is given', function(done) {
image = draw.image(imageUrl).loaded(function() {
expect(image.node.getAttribute('height')).toBe('1')
expect(image.node.getAttribute('width')).toBe('1')
done()
})
})
it('should set width and height if size is given', function(done) {
image = draw.image(imageUrl, 100, 100).loaded(function() {
expect(image.node.getAttribute('height')).toBe('100')
expect(image.node.getAttribute('width')).toBe('100')
done()
})
})
it('returns itself when no url given', function() {
var img = new SVG.Image()
expect(img.load()).toBe(img)
})
})
describe('loaded()', function() {
beforeEach(function(done) {
loadCb = {cb: function(){ done() }}
errorCb = jasmine.createSpy('errorCb')
spyOn(loadCb, 'cb').and.callThrough()
image = draw.image(imageUrl, 100, 100).loaded(loadCb.cb).error(errorCb)
})
it('should set the load callback', function() {
expect(image._loaded).toBe(loadCb.cb)
})
it('executes the load callback', function() {
expect(loadCb.cb).toHaveBeenCalledWith({
width: 1,
height: 1,
ratio: 1,
url: jasmine.any(String)
})
})
it('does not execute the error callback', function() {
expect(errorCb).not.toHaveBeenCalled()
})
})
describe('error()', function() {
beforeEach(function(done) {
loadCb = jasmine.createSpy('loadCb')
errorCb = {cb: function(){ done() }}
spyOn(errorCb, 'cb').and.callThrough()
image = draw.image('not_existant.jpg', 100, 100).loaded(loadCb).error(errorCb.cb)
})
it('should set the error callback', function() {
expect(image._error).toBe(errorCb.cb)
})
it('executes the error callback', function() {
expect(errorCb.cb).toHaveBeenCalledWith(jasmine.any(window.Event))
})
it('does not execute the load callback', function() {
expect(loadCb).not.toHaveBeenCalled()
})
})
describe('x()', function() {
it('should return the value of x without an argument', function() {
expect(image.x()).toBe(0)
})
it('should set the value of x with the first argument', function() {
image.x(123)
var box = image.bbox()
expect(box.x).toBe(123)
})
})
describe('y()', function() {
it('should return the value of y without an argument', function() {
expect(image.y()).toBe(0)
})
it('should set the value of y with the first argument', function() {
image.y(345)
var box = image.bbox()
expect(box.y).toBe(345)
})
})
describe('cx()', function() {
it('should return the value of cx without an argument', function() {
expect(image.cx()).toBe(50)
})
it('should set the value of cx with the first argument', function() {
image.cx(123)
var box = image.bbox()
expect(box.cx).toBe(123)
})
})
describe('cy()', function() {
it('should return the value of cy without an argument', function() {
expect(image.cy()).toBe(50)
})
it('should set the value of cy with the first argument', function() {
image.cy(345)
var box = image.bbox()
expect(box.cy).toBe(345)
})
})
describe('move()', function() {
it('should set the x and y position', function() {
image.move(123,456)
expect(image.node.getAttribute('x')).toBe('123')
expect(image.node.getAttribute('y')).toBe('456')
})
})
describe('dx()', function() {
it('moves the x positon of the element relative to the current position', function() {
image.move(50,60)
image.dx(100)
expect(image.node.getAttribute('x')).toBe('150')
})
})
describe('dy()', function() {
it('moves the y positon of the element relative to the current position', function() {
image.move(50,60)
image.dy(120)
expect(image.node.getAttribute('y')).toBe('180')
})
})
describe('dmove()', function() {
it('moves the x and y positon of the element relative to the current position', function() {
image.move(50,60)
image.dmove(80, 25)
expect(image.node.getAttribute('x')).toBe('130')
expect(image.node.getAttribute('y')).toBe('85')
})
})
describe('center()', function() {
it('should set the cx and cy position', function() {
image.center(321,567)
var box = image.bbox()
expect(box.cx).toBe(321)
expect(box.cy).toBe(567)
})
})
describe('width()', function() {
it('sets the width of the element', function() {
image.width(789)
expect(image.node.getAttribute('width')).toBe('789')
})
it('gets the width of the element if the argument is null', function() {
expect(image.width().toString()).toBe(image.node.getAttribute('width'))
})
})
describe('height()', function() {
it('sets the height of the element', function() {
image.height(1236)
expect(image.node.getAttribute('height')).toBe('1236')
})
it('gets the height of the element if the argument is null', function() {
expect(image.height().toString()).toBe(image.node.getAttribute('height'))
})
})
describe('size()', function() {
it('should define the width and height of the element', function() {
image.size(987,654)
expect(image.node.getAttribute('width')).toBe('987')
expect(image.node.getAttribute('height')).toBe('654')
})
it('defines the width and height proportionally with only the width value given', function() {
var box = image.bbox()
image.size(500)
expect(image.width()).toBe(500)
expect(image.width() / image.height()).toBe(box.width / box.height)
})
it('defines the width and height proportionally with only the height value given', function() {
var box = image.bbox()
image.size(null, 525)
expect(image.height()).toBe(525)
expect(image.width() / image.height()).toBe(box.width / box.height)
})
})
describe('scale()', function() {
it('should scale the element universally with one argument', function() {
var box = image.scale(2).rbox()
expect(box.width).toBe(image.attr('width') * 2)
expect(box.height).toBe(image.attr('height') * 2)
})
it('should scale the element over individual x and y axes with two arguments', function() {
var box = image.scale(2, 3.5).rbox()
expect(box.width).toBe(image.attr('width') * 2)
expect(box.height).toBe(image.attr('height') * 3.5)
})
})
describe('translate()', function() {
it('should set the translation of an element', function() {
image.transform({ x: 12, y: 12 })
expect(image.node.getAttribute('transform')).toBe('matrix(1,0,0,1,12,12)')
})
})
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 | 2 | describe('Line', function() {
var line
beforeEach(function() {
line = draw.line(0,100,100,0)
})
afterEach(function() {
draw.clear()
})
// #487
describe('()', function(){
it('will take an array as input', function(){
line = draw.line([[0,100],[100,0]])
var attrs = line.attr()
expect(attrs.x1).toBe(0)
expect(attrs.y1).toBe(100)
expect(attrs.x2).toBe(100)
expect(attrs.y2).toBe(0)
})
it('falls back to a line with its two points at [0,0] without an argument', function() {
line = draw.line()
var attrs = line.attr()
expect(attrs.x1).toBe(0)
expect(attrs.y1).toBe(0)
expect(attrs.x2).toBe(0)
expect(attrs.y2).toBe(0)
})
})
describe('x()', function() {
it('should return the value of x without an argument', function() {
expect(line.x()).toBe(0)
})
it('should set the value of x with the first argument', function() {
line.x(123)
var box = line.bbox()
expect(box.x).toBe(123)
})
})
describe('y()', function() {
it('should return the value of y without an argument', function() {
expect(line.y()).toBe(0)
})
it('should set the value of y with the first argument', function() {
line.y(345)
var box = line.bbox()
expect(box.y).toBe(345)
})
})
describe('cx()', function() {
it('should return the value of cx without an argument', function() {
expect(line.cx()).toBe(50)
})
it('should set the value of cx with the first argument', function() {
line.cx(123)
var box = line.bbox()
expect(box.cx).toBe(123)
})
})
describe('cy()', function() {
it('should return the value of cy without an argument', function() {
expect(line.cy()).toBe(50)
})
it('should set the value of cy with the first argument', function() {
line.cy(345)
var box = line.bbox()
expect(box.cy).toBe(345)
})
})
describe('move()', function() {
it('should set the x and y position', function() {
line.move(123,456)
var box = line.bbox()
expect(box.x).toBe(123)
expect(box.y + box.height).toBe(556)
expect(box.x + box.width).toBe(223)
expect(box.y).toBe(456)
})
})
describe('dx()', function() {
it('moves the x positon of the element relative to the current position', function() {
line.move(50,60)
line.dx(100)
var box = line.bbox()
expect(box.x).toBe(150)
expect(box.y + box.height).toBe(160)
expect(box.x + box.width).toBe(250)
expect(box.y).toBe(60)
})
})
describe('dy()', function() {
it('moves the y positon of the element relative to the current position', function() {
line.move(50, 60)
line.dy(120)
var box = line.bbox()
expect(box.x).toBe(50)
expect(box.y + box.height).toBe(280)
expect(box.x + box.width).toBe(150)
expect(box.y).toBe(180)
})
})
describe('dmove()', function() {
it('moves the x and y positon of the element relative to the current position', function() {
line.move(50,60)
line.dmove(80, 25)
var box = line.bbox()
expect(box.x).toBe(130)
expect(box.y + box.height).toBe(185)
expect(box.x + box.width).toBe(230)
expect(box.y).toBe(85)
})
})
describe('center()', function() {
it('should set the cx and cy position', function() {
line.center(321,567)
var box = line.bbox()
expect(box.x).toBe(271)
expect(box.y + box.height).toBe(617)
expect(box.x + box.width).toBe(371)
expect(box.y).toBe(517)
})
})
describe('width()', function() {
it('sets the width of the element', function() {
line.width(400)
var box = line.bbox()
expect(box.x).toBe(0)
expect(box.x + box.width).toBe(400)
})
it('get the width of the element without argument', function() {
line.width(123)
var box = line.bbox()
expect(line.width()).toBe(box.width)
})
})
describe('height()', function() {
it('sets the height of the element', function() {
line.height(300)
var box = line.bbox()
expect(box.y).toBe(0)
expect(box.y + box.height).toBe(300)
})
it('gets the height of the element without argument', function() {
line.height(456)
var box = line.bbox()
expect(line.height()).toBe(box.height)
})
})
describe('size()', function() {
it('should define the width and height of the element', function() {
line.size(987,654)
var box = line.bbox()
expect(box.x).toBe(0)
expect(box.y + box.height).toBe(654)
expect(box.x + box.width).toBe(987)
expect(box.y).toBe(0)
})
it('defines the width and height proportionally with only the width value given', function() {
var box = line.bbox()
line.size(500)
expect(line.width()).toBe(500)
expect(line.width() / line.height()).toBe(box.width / box.height)
})
it('defines the width and height proportionally with only the height value given', function() {
var box = line.bbox()
line.size(null, 525)
expect(line.height()).toBe(525)
expect(line.width() / line.height()).toBe(box.width / box.height)
})
})
describe('scale()', function() {
it('should scale the element universally with one argument', function() {
var box1 = line.rbox()
, box2 = line.scale(2).rbox()
expect(box2.width).toBe(box1.width * 2)
expect(box2.height).toBe(box1.height * 2)
})
it('should scale the element over individual x and y axes with two arguments', function() {
var box1 = line.rbox()
, box2 = line.scale(2,3.5).rbox()
expect(box2.width).toBe(box1.width * 2)
expect(box2.height).toBe(box1.height * 3.5)
})
})
describe('translate()', function() {
it('should set the translation of an element', function() {
line.transform({ x: 12, y: 12 })
expect(line.node.getAttribute('transform')).toBe('matrix(1,0,0,1,12,12)')
})
})
describe('plot()', function() {
it('should update the start and end points', function() {
line.plot(100,200,300,400)
var box = line.bbox()
expect(box.x).toBe(100)
expect(box.y).toBe(200)
expect(box.x + box.width).toBe(300)
expect(box.y + box.height).toBe(400)
})
it('change the x1,y1,x2,y2 attributes of the underlying line node when a string is passed', function() {
expect(line.plot('100,50 200,10')).toBe(line)
var attrs = line.attr()
expect(attrs.x1).toBe(100)
expect(attrs.y1).toBe(50)
expect(attrs.x2).toBe(200)
expect(attrs.y2).toBe(10)
})
it('change the x1,y1,x2,y2 attributes of the underlying line node when 4 numbers are passed', function() {
expect(line.plot(45, 24, 220, 300)).toBe(line)
var attrs = line.attr()
expect(attrs.x1).toBe(45)
expect(attrs.y1).toBe(24)
expect(attrs.x2).toBe(220)
expect(attrs.y2).toBe(300)
})
it('return the coordinates in a point array when no arguments are passed', function () {
var attrs = line.attr()
, pointArray = new SVG.PointArray([[attrs.x1, attrs.y1], [attrs.x2, attrs.y2]])
expect(line.plot()).toEqual(pointArray)
})
})
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 | 2 | describe('Marker', function() {
describe('on a container element', function() {
var marker
beforeEach(function() {
marker = draw.marker(10, 12, function(add) {
add.rect(10, 12)
this.ref(5, 6)
})
})
it('creates an instance of SVG.Marker', function() {
expect(marker instanceof SVG.Marker).toBeTruthy()
})
it('creates marker in defs', function() {
expect(marker.parent() instanceof SVG.Defs).toBeTruthy()
})
describe('marker()', function() {
it('returns the marker element', function() {
expect(marker = draw.marker(10, 12)).toBe(marker)
})
it('sets the refX to half of the given width', function() {
marker = draw.marker(10, 12)
expect(marker.node.getAttribute('refX')).toBe('5')
})
it('sets the refY to half of the given height', function() {
marker = draw.marker(13, 15)
expect(marker.node.getAttribute('refY')).toBe('7.5')
})
})
})
describe('on a target path', function() {
var path, marker
beforeEach(function() {
path = draw.path('M 100 200 C 200 100 300 0 400 100 C 500 200 600 300 700 200 C 800 100 900 100 900 100')
path.marker('mid', 10, 12, function(add) {
add.rect(10, 12)
this.ref(5, 6)
})
marker = path.marker('mid', 10, 10)
})
it('creates an instance of SVG.Marker', function() {
expect(path.reference('marker-mid') instanceof SVG.Marker).toBeTruthy()
})
describe('marker()', function() {
it('returns the target element', function() {
expect(path.marker('start', 10, 12)).toBe(path)
})
it('creates a marker and applies it to the marker-start attribute', function() {
path.marker('start', 10, 12)
marker = path.reference('marker-start')
expect(path.node.getAttribute('marker-start')).toBe(marker.toString())
})
it('creates a marker and applies it to the marker-mid attribute', function() {
path.marker('mid', 10, 12)
marker = path.reference('marker-mid')
expect(path.node.getAttribute('marker-mid')).toBe(marker.toString())
})
it('creates a marker and applies it to the marker-end attribute', function() {
path.marker('end', 10, 12)
marker = path.reference('marker-end')
expect(path.node.getAttribute('marker-end')).toBe(marker.toString())
})
it('accepts an instance of an existing marker element as the second argument', function() {
marker = draw.marker(11, 11)
path.marker('mid', marker)
expect(path.node.getAttribute('marker-mid')).toBe(marker.toString())
})
})
})
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | 2 | describe('Mask', function() {
var rect, circle
beforeEach(function() {
rect = draw.rect(100,100)
circle = draw.circle(100).move(50, 50).fill('#fff')
rect.maskWith(circle)
})
afterEach(function() {
draw.clear()
})
it('moves the masking element to a new mask node', function() {
expect(circle.parent() instanceof SVG.Mask).toBe(true)
})
it('creates the mask node in the defs node', function() {
expect(circle.parent().parent()).toBe(draw.defs())
})
it('sets the "mask" attribute on the masked element with the mask id', function() {
expect(rect.attr('mask')).toBe('url("#' + circle.parent().attr('id') + '")')
})
it('references the mask element in the masked element', function() {
expect(rect.masker).toBe(circle.parent())
})
it('references the masked element in the mask target list', function() {
expect(rect.masker.targets.indexOf(rect) > -1).toBe(true)
})
it('reuses mask element when mask was given', function() {
var mask = rect.masker
expect(draw.rect(100,100).maskWith(mask).masker).toBe(mask)
})
it('unmasks all masked elements when being removed', function() {
rect.masker.remove()
expect(rect.attr('mask')).toBe(undefined)
})
describe('unmask()', function() {
it('clears the "mask" attribute on the masked element', function() {
rect.unmask()
expect(rect.attr('mask')).toBe(undefined)
})
it('removes the reference to the masking element', function() {
rect.unmask()
expect(rect.masker).toBe(undefined)
})
it('returns the element itslef', function() {
expect(rect.unmask()).toBe(rect)
})
})
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 | 2 | describe('Matrix', function() {
var matrix
describe('initialization', function() {
describe('without a source', function() {
beforeEach(function() {
matrix = new SVG.Matrix
})
it('creates a new matrix with default values', function() {
expect(matrix.a).toBe(1)
expect(matrix.b).toBe(0)
expect(matrix.c).toBe(0)
expect(matrix.d).toBe(1)
expect(matrix.e).toBe(0)
expect(matrix.f).toBe(0)
})
describe('extract()', function() {
var extract
beforeEach(function() {
extract = matrix.extract()
})
it('parses translation values', function() {
expect(extract.x).toBe(0)
expect(extract.y).toBe(0)
})
it('parses skew values', function() {
expect(extract.skewX).toBe(0)
expect(extract.skewY).toBe(0)
})
it('parses scale values', function() {
expect(extract.scaleX).toBe(1)
expect(extract.scaleY).toBe(1)
})
it('parses rotatoin value', function() {
expect(extract.rotation).toBe(0)
})
})
describe('toString()' , function() {
it('exports correctly to a string', function() {
expect(matrix.toString()).toBe('matrix(1,0,0,1,0,0)')
})
})
})
describe('with an element given', function() {
var rect
beforeEach(function() {
rect = draw.rect(100, 100)
.transform({ rotation: -10 }, true)
.transform({ x: 40, y: 50 }, true)
.transform({ scale: 2 }, true)
matrix = new SVG.Matrix(rect)
})
it('parses the current transform matrix from an element', function() {
expect(matrix.a).toBeCloseTo(1.9696155786514282)
expect(matrix.b).toBeCloseTo(-0.3472963869571686)
expect(matrix.c).toBeCloseTo(0.3472963869571686)
expect(matrix.d).toBeCloseTo(1.9696155786514282)
expect(matrix.e).toBeCloseTo(-17.770875930786133)
expect(matrix.f).toBeCloseTo(11.178505897521973)
})
describe('extract()', function() {
it('parses translation values', function() {
var extract = new SVG.Matrix(draw.rect(100, 100).translate(40, 50)).extract()
expect(extract.x).toBeCloseTo(40)
expect(extract.y).toBeCloseTo(50)
})
it('parses skewX value', function() {
var extract = new SVG.Matrix(draw.rect(100, 100).skew(25, 0)).extract()
expect(extract.skewX).toBeCloseTo(25)
})
it('parses skewY value', function() {
var extract = new SVG.Matrix(draw.rect(100, 100).skew(0, 20)).extract()
expect(extract.skewY).toBeCloseTo(20)
})
it('parses scale values', function() {
var extract = new SVG.Matrix(draw.rect(100, 100).scale(2, 3)).extract()
expect(extract.scaleX).toBeCloseTo(2)
expect(extract.scaleY).toBeCloseTo(3)
})
it('parses rotatoin value', function() {
var extract = new SVG.Matrix(draw.rect(100, 100).rotate(-100)).extract()
expect(extract.rotation).toBeCloseTo(-100)
})
})
})
describe('with a string given', function() {
it('parses the string value correctly', function() {
var matrix = new SVG.Matrix('2, 0, 0, 2, 100, 50')
expect(matrix.a).toBe(2)
expect(matrix.b).toBe(0)
expect(matrix.c).toBe(0)
expect(matrix.d).toBe(2)
expect(matrix.e).toBe(100)
expect(matrix.f).toBe(50)
})
})
describe('with an array given', function() {
it('parses the array correctly', function() {
var matrix = new SVG.Matrix([2, 0, 0, 2, 100, 50])
expect(matrix.a).toBe(2)
expect(matrix.b).toBe(0)
expect(matrix.c).toBe(0)
expect(matrix.d).toBe(2)
expect(matrix.e).toBe(100)
expect(matrix.f).toBe(50)
})
})
describe('with an object given', function() {
it('parses the object correctly', function() {
var matrix = new SVG.Matrix({a:2, b:0, c:0, d:2, e:100, f:50})
expect(matrix.a).toBe(2)
expect(matrix.b).toBe(0)
expect(matrix.c).toBe(0)
expect(matrix.d).toBe(2)
expect(matrix.e).toBe(100)
expect(matrix.f).toBe(50)
})
})
describe('with 6 arguments given', function() {
it('parses the arguments correctly', function() {
var matrix = new SVG.Matrix(2, 0, 0, 2, 100, 50)
expect(matrix.a).toBe(2)
expect(matrix.b).toBe(0)
expect(matrix.c).toBe(0)
expect(matrix.d).toBe(2)
expect(matrix.e).toBe(100)
expect(matrix.f).toBe(50)
})
})
})
describe('clone()', function() {
it('returns a clone of the matrix', function() {
var matrix = new SVG.Matrix(2, 0, 0, 5, 0, 0)
, clone = matrix.clone()
expect(matrix).not.toBe(clone)
for(var i in 'abcdef') {
expect(matrix[i]).toEqual(clone[i])
}
})
})
describe('morph()', function() {
it('stores a given matrix for morphing', function() {
var matrix1 = new SVG.Matrix(2, 0, 0, 5, 0, 0)
, matrix2 = new SVG.Matrix(1, 0, 0, 1, 4, 3)
matrix1.morph(matrix2)
expect(matrix1.destination).toEqual(matrix2)
})
it('stores a clone, not the given matrix itself', function() {
var matrix1 = new SVG.Matrix(2, 0, 0, 5, 0, 0)
, matrix2 = new SVG.Matrix(1, 0, 0, 1, 4, 3)
matrix1.morph(matrix2)
expect(matrix1.destination).not.toBe(matrix2)
})
})
describe('at()', function() {
it('returns a morphed array at a given position', function() {
var matrix1 = new SVG.Matrix(2, 0, 0, 5, 0, 0)
, matrix2 = new SVG.Matrix(1, 0, 0, 1, 4, 3)
, matrix3 = matrix1.morph(matrix2).at(0.5)
expect(matrix1.toString()).toBe('matrix(2,0,0,5,0,0)')
expect(matrix2.toString()).toBe('matrix(1,0,0,1,4,3)')
expect(matrix3.toString()).toBe('matrix(1.5,0,0,3,2,1.5)')
})
it('returns itself when no destination specified', function() {
var matrix = new SVG.Matrix(2, 0, 0, 5, 0, 0)
expect(matrix.at(0.5)).toBe(matrix)
})
})
describe('multiply()', function() {
it('multiplies two matices', function() {
var matrix1 = new SVG.Matrix(2, 0, 0, 5, 0, 0)
, matrix2 = new SVG.Matrix(1, 0, 0, 1, 4, 3)
, matrix3 = matrix1.multiply(matrix2)
expect(matrix1.toString()).toBe('matrix(2,0,0,5,0,0)')
expect(matrix2.toString()).toBe('matrix(1,0,0,1,4,3)')
expect(matrix3.toString()).toBe('matrix(2,0,0,5,8,15)')
})
it('accepts matrices in any form', function() {
var matrix1 = new SVG.Matrix(2, 0, 0, 5, 0, 0)
, matrix2 = matrix1.multiply('1,0,0,1,4,3')
expect(matrix1.toString()).toBe('matrix(2,0,0,5,0,0)')
expect(matrix2.toString()).toBe('matrix(2,0,0,5,8,15)')
})
})
describe('inverse()', function() {
it('inverses matrix', function() {
var matrix1 = new SVG.Matrix(2, 0, 0, 5, 4, 3)
, matrix2 = matrix1.inverse()
, abcdef = [0.5,0,0,0.2,-2,-0.6]
expect(matrix1.toString()).toBe('matrix(2,0,0,5,4,3)')
for(var i in 'abcdef') {
expect(matrix2['abcdef'[i]]).toBeCloseTo(abcdef[i])
}
})
})
describe('translate()', function() {
it('translates matrix by given x and y values', function() {
var matrix = new SVG.Matrix(1, 0, 0, 1, 4, 3).translate(10, 12.5)
expect(matrix.e).toBe(14)
expect(matrix.f).toBe(15.5)
})
})
describe('scale()', function() {
it('performs a uniformal scale with one value', function() {
var matrix = new SVG.Matrix(1, 0, 0, 1, 4, 3).scale(3)
expect(matrix.a).toBe(3)
expect(matrix.d).toBe(3)
expect(matrix.e).toBe(4)
expect(matrix.f).toBe(3)
})
it('performs a non-uniformal scale with two values', function() {
var matrix = new SVG.Matrix(1, 0, 0, 1, 4, 3).scale(2.5, 3.5)
expect(matrix.a).toBe(2.5)
expect(matrix.d).toBe(3.5)
expect(matrix.e).toBe(4)
expect(matrix.f).toBe(3)
})
it('performs a uniformal scale at a given center point with three values', function() {
var matrix = new SVG.Matrix(1, 0, 0, 1, 4, 3).scale(3, 150, 100)
expect(matrix.a).toBe(3)
expect(matrix.d).toBe(3)
expect(matrix.e).toBe(-296)
expect(matrix.f).toBe(-197)
})
it('performs a non-uniformal scale at a given center point with four values', function() {
var matrix = new SVG.Matrix(1, 0, 0, 1, 4, 3).scale(3, 2, 150, 100)
expect(matrix.a).toBe(3)
expect(matrix.d).toBe(2)
expect(matrix.e).toBe(-296)
expect(matrix.f).toBe(-97)
})
})
describe('rotate()', function() {
it('performs a rotation with one argument', function() {
var matrix = new SVG.Matrix(1, 0, 0, 1, 4, 3).rotate(30)
expect(matrix.a).toBeCloseTo(0.8660254037844387)
expect(matrix.d).toBeCloseTo(0.8660254037844387)
expect(matrix.e).toBe(4)
expect(matrix.f).toBe(3)
})
it('performs a rotation on a given point with three arguments', function() {
var matrix = new SVG.Matrix(1, 0, 0, 1, 4, 3).rotate(30, 150, 100)
expect(matrix.a).toBeCloseTo(0.8660254037844387)
expect(matrix.d).toBeCloseTo(0.8660254037844387)
expect(matrix.e).toBeCloseTo(74.0961894323342)
expect(matrix.f).toBeCloseTo(-58.60254037844388)
})
})
describe('flip()', function() {
describe('with x given', function() {
it('performs a flip over the horizontal axis with one argument', function() {
var matrix = new SVG.Matrix(1, 0, 0, 1, 4, 3).flip('x')
expect(matrix.a).toBe(-1)
expect(matrix.d).toBe(1)
expect(matrix.e).toBe(4)
expect(matrix.f).toBe(3)
})
it('performs a flip over the horizontal axis over a given point with two arguments', function() {
var matrix = new SVG.Matrix(1, 0, 0, 1, 4, 3).flip('x', 150)
expect(matrix.a).toBe(-1)
expect(matrix.d).toBe(1)
expect(matrix.e).toBe(304)
expect(matrix.f).toBe(3)
})
})
describe('with y given', function() {
it('performs a flip over the vertical axis with one argument', function() {
var matrix = new SVG.Matrix(1, 0, 0, 1, 4, 3).flip('y')
expect(matrix.a).toBe(1)
expect(matrix.d).toBe(-1)
expect(matrix.e).toBe(4)
expect(matrix.f).toBe(3)
})
it('performs a flip over the vertical axis over a given point with two arguments', function() {
var matrix = new SVG.Matrix(1, 0, 0, 1, 4, 3).flip('y', 100)
expect(matrix.a).toBe(1)
expect(matrix.d).toBe(-1)
expect(matrix.e).toBe(4)
expect(matrix.f).toBe(203)
})
})
describe('with no axis given', function() {
it('performs a flip over the horizontal and vertical axis with no argument', function() {
var matrix = new SVG.Matrix(1, 0, 0, 1, 4, 3).flip()
expect(matrix.a).toBe(-1)
expect(matrix.d).toBe(-1)
expect(matrix.e).toBe(4)
expect(matrix.f).toBe(3)
})
it('performs a flip over the horizontal and vertical axis over a given point with one argument that represent both coordinates', function() {
var matrix = new SVG.Matrix(1, 0, 0, 1, 4, 3).flip(100)
expect(matrix.a).toBe(-1)
expect(matrix.d).toBe(-1)
expect(matrix.e).toBe(204)
expect(matrix.f).toBe(203)
})
it('performs a flip over the horizontal and vertical axis over a given point with two arguments', function() {
var matrix = new SVG.Matrix(1, 0, 0, 1, 4, 3).flip(50, 100)
expect(matrix.a).toBe(-1)
expect(matrix.d).toBe(-1)
expect(matrix.e).toBe(104)
expect(matrix.f).toBe(203)
})
})
})
describe('skew()', function() {
it('performs a uniformal skew with one value', function() {
var matrix = new SVG.Matrix(1, 0, 0, 1, 4, 3).skew(14)
expect(matrix.a).toBe(1)
expect(matrix.b).toBeCloseTo(0.24932800284318)
expect(matrix.c).toBeCloseTo(0.24932800284318)
expect(matrix.d).toBe(1)
expect(matrix.e).toBe(4)
expect(matrix.f).toBe(3)
})
it('performs a non-uniformal skew with two values', function() {
var matrix = new SVG.Matrix(1, 0, 0, 1, 4, 3).skew(8, 5)
expect(matrix.a).toBe(1)
expect(matrix.b).toBeCloseTo(0.087488663525924)
expect(matrix.c).toBeCloseTo(0.14054083470239)
expect(matrix.d).toBe(1)
expect(matrix.e).toBe(4)
expect(matrix.f).toBe(3)
})
it('performs a uniformal skew at a given center point with three values', function() {
var matrix = new SVG.Matrix(1, 0, 0, 1, 4, 3).skew(3, 150, 100)
expect(matrix.a).toBe(1)
expect(matrix.b).toBeCloseTo(0.052407779283041)
expect(matrix.c).toBeCloseTo(0.052407779283041)
expect(matrix.d).toBe(1)
expect(matrix.e).toBeCloseTo(-1.2407779283)
expect(matrix.f).toBeCloseTo(-4.8611668924562)
})
it('performs a non-uniformal skew at a given center point with four values', function() {
var matrix = new SVG.Matrix(1, 0, 0, 1, 4, 3).skew(9, 7, 150, 100)
expect(matrix.a).toBe(1)
expect(matrix.b).toBeCloseTo(0.1227845609029)
expect(matrix.c).toBeCloseTo(0.15838444032454)
expect(matrix.d).toBe(1)
expect(matrix.e).toBeCloseTo(-11.83844403245)
expect(matrix.f).toBeCloseTo(-15.417684135435)
})
it('can be chained', function(){
var matrix = new SVG.Matrix(1, 0, 0, 1, 4, 3).skew(9, 7).skew(20, 40)
expect(matrix.a).toBeCloseTo(1.1329003254605)
expect(matrix.b).toBeCloseTo(0.96188419208018)
expect(matrix.c).toBeCloseTo(0.52235467459074)
expect(matrix.d).toBeCloseTo(1.0446899253961)
expect(matrix.e).toBe(4)
expect(matrix.f).toBe(3)
})
})
describe('skewX', function(){
it('performs a skew along the x axis with one value', function() {
var matrix = new SVG.Matrix(1, 0, 0, 1, 4, 3).skewX(12)
expect(matrix.a).toBe(1)
expect(matrix.b).toBe(0)
expect(matrix.c).toBeCloseTo(0.21255656167002)
expect(matrix.d).toBe(1)
expect(matrix.e).toBe(4)
expect(matrix.f).toBe(3)
})
it('performs a skew along the x axis at a given center point with three values', function() {
var matrix = new SVG.Matrix(1, 0, 0, 1, 4, 3).skewX(5, 150, 100)
expect(matrix.a).toBe(1)
expect(matrix.b).toBe(0)
expect(matrix.c).toBeCloseTo(0.087488663525924)
expect(matrix.d).toBe(1)
expect(matrix.e).toBeCloseTo(-4.74886635259)
expect(matrix.f).toBe(3)
})
})
describe('skewY', function(){
it('performs a skew along the y axis with one value', function() {
var matrix = new SVG.Matrix(1, 0, 0, 1, 4, 3).skewY(12)
expect(matrix.a).toBe(1)
expect(matrix.b).toBeCloseTo(0.21255656167002)
expect(matrix.c).toBe(0)
expect(matrix.d).toBe(1)
expect(matrix.e).toBe(4)
expect(matrix.f).toBe(3)
})
it('performs a skew along the y axis at a given center point with three values', function() {
var matrix = new SVG.Matrix(1, 0, 0, 1, 4, 3).skewY(5, 150, 100)
expect(matrix.a).toBe(1)
expect(matrix.b).toBeCloseTo(0.087488663525924)
expect(matrix.c).toBe(0)
expect(matrix.d).toBe(1)
expect(matrix.e).toBe(4)
expect(matrix.f).toBeCloseTo(-10.123299528889)
})
})
describe('native()', function() {
it('returns the node reference', function() {
expect(new SVG.Matrix().native() instanceof window.SVGMatrix).toBeTruthy()
})
})
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | 2 | describe('Memory', function () {
var rect, circle
beforeEach(function() {
rect = draw.rect(100,120)
circle = draw.circle(100)
})
afterEach(function() {
draw.clear()
})
describe('remember()', function() {
it('accepts an object with values', function() {
rect.remember({ some: {cool:'and',nested:'stuff',foo:5} })
expect(rect.remember('some').foo).toBe(5)
})
it('accepts key / value arguments', function() {
rect.remember('fill', rect.attr('fill'))
rect.fill('#f09')
expect(rect.remember('fill')).toBe('#000000')
})
it('acts as a getter with one string argument', function() {
rect.remember('opacity', 0.85)
expect(rect.remember('opacity')).toBe(0.85)
})
it('saves values to individual objects', function() {
rect.remember('opacity', 0.85)
circle.remember('opacity', 0.5)
expect(rect.remember('opacity')).toBe(0.85)
expect(circle.remember('opacity')).toBe(0.5)
})
})
describe('forget()', function() {
it('deletes a given memory', function() {
rect.remember({ grass: 'is green', one: 1 })
rect.forget('grass')
expect(rect.remember('grass')).toBe(undefined)
expect(rect.remember('one')).toBe(1)
})
it('accepts multiple arguments as different memories', function() {
rect.remember({ grass: 'might be purple', two: 2, sea: true })
rect.forget('grass', 'sea')
expect(rect.remember('grass')).toBe(undefined)
expect(rect.remember('sea')).toBe(undefined)
expect(rect.remember('two')).toBe(2)
})
it('clears the whole memory without arguments', function() {
rect.remember({ grass: 'is never pink', three: 3, tree: true })
rect.forget()
expect(rect.remember('grass')).toBe(undefined)
expect(rect.remember('tree')).toBe(undefined)
expect(rect.remember('three')).toBe(undefined)
})
})
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 2 | describe('Nested', function() {
afterEach(function() {
draw.clear()
})
describe('()', function() {
it('creates a nested svg of type SVG.Nested', function() {
expect(draw.nested() instanceof SVG.Nested).toBeTruthy()
})
})
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 | 2 | describe('Number', function() {
var number
beforeEach(function() {
number = new SVG.Number
})
describe('new', function() {
it('is zero', function() {
expect(number.value).toBe(0)
})
it('has a blank unit', function() {
expect(number.unit).toBe('')
})
it('accepts the unit as a second argument', function() {
number = new SVG.Number(30, '%')
expect(number.value).toBe(30)
expect(number.unit).toBe('%')
})
it('parses a pixel value', function() {
number = new SVG.Number('20px')
expect(number.value).toBe(20)
expect(number.unit).toBe('px')
})
it('parses a percent value', function() {
number = new SVG.Number('99%')
expect(number.value).toBe(0.99)
expect(number.unit).toBe('%')
})
it('parses a seconds value', function() {
number = new SVG.Number('2s')
expect(number.value).toBe(2000)
expect(number.unit).toBe('s')
})
it('parses a negative percent value', function() {
number = new SVG.Number('-89%')
expect(number.value).toBe(-0.89)
expect(number.unit).toBe('%')
})
it('falls back to 0 if given value is NaN', function() {
number = new SVG.Number(NaN)
expect(number.value).toBe(0)
})
it('falls back to maximum value if given number is positive infinite', function() {
number = new SVG.Number(1.7976931348623157E+10308)
expect(number.value).toBe(3.4e+38)
})
it('falls back to minimum value if given number is negative infinite', function() {
number = new SVG.Number(-1.7976931348623157E+10308)
expect(number.value).toBe(-3.4e+38)
})
})
describe('toString()', function() {
it('converts the number to a string', function() {
expect(number.toString()).toBe('0')
})
it('appends the unit', function() {
number.value = 1.21
number.unit = 'px'
expect(number.toString()).toBe('1.21px')
})
it('converts percent values properly', function() {
number.value = 1.36
number.unit = '%'
expect(number.toString()).toBe('136%')
})
it('converts second values properly', function() {
number.value = 2500
number.unit = 's'
expect(number.toString()).toBe('2.5s')
})
})
describe('valueOf()', function() {
it('returns a numeric value for default units', function() {
expect(typeof number.valueOf()).toBe('number')
number = new SVG.Number('12')
expect(typeof number.valueOf()).toBe('number')
number = new SVG.Number(13)
expect(typeof number.valueOf()).toBe('number')
})
it('returns a numeric value for pixel units', function() {
number = new SVG.Number('10px')
expect(typeof number.valueOf()).toBe('number')
})
it('returns a numeric value for percent units', function() {
number = new SVG.Number('20%')
expect(typeof number.valueOf()).toBe('number')
})
it('converts to a primitive when multiplying', function() {
number.value = 80
expect(number * 4).toBe(320)
})
})
describe('to()', function() {
beforeEach(function() {
number = number.plus(4)
})
it('returns a new instance', function() {
expect(number.to('em')).not.toBe(number)
expect(number.to('em') instanceof SVG.Number).toBeTruthy()
})
it('changes the unit value', function() {
number = number.to('%')
expect(number.unit).toBe('%')
})
it('changes the output value', function() {
var oldNumber = number.valueOf()
number = number.to('%')
expect(number.toString()).toBe('400%')
})
})
describe('plus()', function() {
it('returns a new instance', function() {
expect(number.plus(4.5)).not.toBe(number)
expect(number.plus(4.5) instanceof SVG.Number).toBeTruthy()
})
it('adds a given number', function() {
expect(number.plus(3.5).valueOf()).toBe(3.5)
})
it('adds a given percentage value', function() {
expect(number.plus('225%').valueOf()).toBe(2.25)
})
it('adds a given pixel value', function() {
expect(number.plus('83px').valueOf()).toBe(83)
})
it('use the unit of this number as the unit of the returned number by default', function (){
expect(new SVG.Number('12s').plus('3%').unit).toBe('s')
})
it('use the unit of the passed number as the unit of the returned number when this number as no unit', function() {
expect(number.plus('15%').unit).toBe('%')
})
})
describe('minus()', function() {
it('subtracts a given number', function() {
expect(number.minus(3.7).valueOf()).toBe(-3.7)
})
it('subtracts a given percentage value', function() {
expect(number.minus('223%').valueOf()).toBe(-2.23)
})
it('subtracts a given pixel value', function() {
expect(number.minus('85px').valueOf()).toBe(-85)
})
it('use the unit of this number as the unit of the returned number by default', function (){
expect(new SVG.Number('12s').minus('3%').unit).toBe('s')
})
it('use the unit of the passed number as the unit of the returned number when this number as no unit', function() {
expect(number.minus('15%').unit).toBe('%')
})
})
describe('times()', function() {
beforeEach(function() {
number = number.plus(4)
})
it('multiplies with a given number', function() {
expect(number.times(3).valueOf()).toBe(12)
})
it('multiplies with a given percentage value', function() {
expect(number.times('110%').valueOf()).toBe(4.4)
})
it('multiplies with a given pixel value', function() {
expect(number.times('85px').valueOf()).toBe(340)
})
it('use the unit of this number as the unit of the returned number by default', function (){
expect(new SVG.Number('12s').times('3%').unit).toBe('s')
})
it('use the unit of the passed number as the unit of the returned number when this number as no unit', function() {
expect(number.times('15%').unit).toBe('%')
})
})
describe('divide()', function() {
beforeEach(function() {
number = number.plus(90)
})
it('divides by a given number', function() {
expect(number.divide(3).valueOf()).toBe(30)
})
it('divides by a given percentage value', function() {
expect(number.divide('3000%').valueOf()).toBe(3)
})
it('divides by a given pixel value', function() {
expect(number.divide('45px').valueOf()).toBe(2)
})
it('use the unit of this number as the unit of the returned number by default', function (){
expect(new SVG.Number('12s').divide('3%').unit).toBe('s')
})
it('use the unit of the passed number as the unit of the returned number when this number as no unit', function() {
expect(number.divide('15%').unit).toBe('%')
})
})
describe('morph()', function() {
it('returns itself', function() {
expect(number.morph(new SVG.Number)).toBe(number)
})
it('prepares the color for morphing', function() {
var destination = new SVG.Number
number.morph(destination)
expect(number.destination).toEqual(destination)
})
it('if the passed object as a relative attribute set to true, destination is relative to the current value', function() {
var n1 = new SVG.Number(3)
, n2 = new SVG.Number(7)
n2.relative = true
n1.morph(n2)
expect(n1.destination.value).toBe(n1.value + n2.value)
})
})
describe('at()', function() {
it('returns a new instance', function() {
var destination = new SVG.Number(200)
var morphed = number.morph(destination).at(0.4)
expect(morphed).not.toBe(number)
expect(morphed).not.toBe(destination)
})
it('morphes number to a given position', function() {
var destination = new SVG.Number(200)
var morphed = number.morph(destination).at(0.4)
expect(morphed.valueOf()).toBe(80)
})
it('morphes number to a given percentage position', function() {
var destination = new SVG.Number('100%')
var morphed = number.morph(destination).at(0.72)
expect(morphed.toString()).toBe('72%')
})
it('use the unit of the destination number as the unit of the returned number by default', function() {
expect(new SVG.Number('100s').morph('50%').at(0.5).unit).toBe('%')
})
it('use the unit of this number as the unit of the returned number when the destination number as no unit', function() {
expect(expect(new SVG.Number('100s').morph(50).at(0.5).unit).toBe('s'))
})
it('returns itself when no destination specified', function() {
expect(number.at(0.5)).toBe(number)
})
})
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 | 2 | describe('Path', function() {
var path
beforeEach(function() {
path = draw.path(svgPath)
})
afterEach(function() {
draw.clear()
})
describe('()', function() {
it('falls back to a single point without an argument', function() {
path = draw.path()
expect(path.attr('d')).toBe('M0 0 ')
})
})
describe('array()', function() {
it('returns an instance of SVG.PathArray', function() {
expect(path.array() instanceof SVG.PathArray).toBeTruthy()
})
it('returns the value stored in the private variable _array', function() {
expect(path.array()).toBe(path._array)
})
})
describe('x()', function() {
it('returns the value of x without an argument', function() {
expect(path.x()).toBe(0)
})
it('sets the value of x with the first argument', function() {
path.x(123)
var box = path.bbox()
expect(box.x).toBe(123)
})
})
describe('y()', function() {
it('returns the value of y without an argument', function() {
expect(path.y()).toBe(0)
})
it('sets the value of y with the first argument', function() {
path.y(345)
var box = path.bbox()
expect(box.y).toBe(345)
})
})
describe('cx()', function() {
it('returns the value of cx without an argument', function() {
expect(path.cx()).toBe(50)
})
it('sets the value of cx with the first argument', function() {
path.cx(123)
var box = path.bbox()
expect(box.cx).toBe(123)
})
})
describe('cy()', function() {
it('returns the value of cy without an argument', function() {
expect(path.cy()).toBe(50)
})
it('sets the value of cy with the first argument', function() {
path.cy(345)
var box = path.bbox()
expect(box.cy).toBe(345)
})
})
describe('move()', function() {
it('sets the x and y position', function() {
path.move(123,456)
var box = path.bbox()
expect(box.x).toBe(123)
expect(box.y).toBe(456)
})
it('sets the x and y position when scaled to half its size', function() {
path.scale(0.5, 0, 0).move(123,456)
var box = path.bbox()
expect(box.x).toBe(123)
expect(box.y).toBe(456)
})
})
describe('dx()', function() {
it('moves the x positon of the element relative to the current position', function() {
path.move(50,60)
path.dx(100)
var box = path.bbox()
expect(box.x).toBe(150)
})
})
describe('dy()', function() {
it('moves the y positon of the element relative to the current position', function() {
path.move(50, 60)
path.dy(120)
var box = path.bbox()
expect(box.y).toBe(180)
})
})
describe('dmove()', function() {
it('moves the x and y positon of the element relative to the current position', function() {
path.move(50,60)
path.dmove(80, 25)
var box = path.bbox()
expect(box.x).toBe(130)
expect(box.y).toBe(85)
})
})
describe('center()', function() {
it('sets the cx and cy position', function() {
path.center(321,567)
var box = path.bbox()
expect(box.x).toBe(271)
expect(box.y).toBe(517)
})
})
describe('width()', function() {
it('sets the width of the element', function() {
path.width(234)
var box = path.bbox()
expect(box.width).toBeCloseTo(234)
})
it('gets the width of the element without an argument', function() {
path.width(456)
expect(path.width()).toBeCloseTo(456)
})
})
describe('height()', function() {
it('sets the height of the element', function() {
path.height(654)
var box = path.bbox()
expect(box.height).toBeCloseTo(654)
})
it('gets the height of the element without an argument', function() {
path.height(321)
expect(path.height()).toBeCloseTo(321)
})
})
describe('size()', function() {
it('defines the width and height of the element', function() {
path.size(987,654)
var box = path.bbox()
expect(box.width).toBeCloseTo(987)
expect(box.height).toBeCloseTo(654)
})
it('defines the width and height proportionally with only the width value given', function() {
var box = path.bbox()
path.size(500)
expect(path.width()).toBeCloseTo(500)
expect(path.width() / path.height()).toBe(box.width / box.height)
})
it('defines the width and height proportionally with only the height value given', function() {
var box = path.bbox()
path.size(null, 525)
expect(path.height()).toBe(525)
expect(path.width() / path.height()).toBeCloseTo(box.width / box.height)
})
})
describe('scale()', function() {
it('should scale the element universally with one argument', function() {
var box1 = path.rbox()
, box2 = path.scale(2).rbox()
expect(box1.width * 2).toBe(box2.width)
expect(box1.height * 2).toBe(box2.height)
})
it('should scale the element over individual x and y axes with two arguments', function() {
var box1 = path.rbox()
, box2 = path.scale(2, 3.5).rbox()
expect(box1.width * 2).toBe(box2.width)
expect(box1.height * 3.5).toBe(box2.height)
})
})
describe('translate()', function() {
it('sets the translation of an element', function() {
path.transform({ x: 12, y: 12 })
expect(path.node.getAttribute('transform')).toBe('matrix(1,0,0,1,12,12)')
})
})
describe('plot()', function() {
it('changes the d attribute of the underlying path node when a string is passed', function() {
var pathString = 'm 3,2 c 0,0 -0,13 8,14 L 5,4'
, pathArray = new SVG.PathArray(pathString)
expect(path.plot(pathString)).toBe(path)
expect(path.attr('d')).toBe(pathString)
})
it('clears the array cache when a value is passed', function() {
path = draw.path([ ['M', 50, 60], ['A', 60, 60, 0, 0, 0, 50, -60], ['z'] ])
expect(path._array instanceof SVG.PathArray).toBeTruthy()
path.plot('m 3,2 c 0,0 -0,13 8,14 L 5,4')
expect(path._array).toBeUndefined()
})
it('applies a given path string value as is', function() {
var pathString = 'm 3,2 c 0,0 -0,13 8,14 L 5,4'
path = draw.path(pathString)
expect(path.attr('d')).toBe(pathString)
})
it('does not parse and cache a given string value to SVG.PathArray', function() {
path = draw.path('m 3,2 c 0,0 -0,13 8,14 L 5,4')
expect(path._array).toBeUndefined()
})
it('caches a given array value', function() {
path = draw.path([ ['M', 50, 60], ['A', 60, 60, 0, 0, 0, 50, -60], ['H', 100], ['L', 20, 30], ['Z'] ])
expect(path._array instanceof SVG.PathArray).toBeTruthy()
})
it('returns the path array when no arguments are passed', function () {
expect(path.plot()).toBe(path.array())
})
})
describe('clear()', function() {
it('clears the cached SVG.PathArray instance', function() {
path = draw.path(svgPath)
path.clear()
expect(path._array).toBeUndefined()
})
})
describe('toString()', function() {
it('renders path array correctly to string', function() {
path = path.plot(['M', 50, 60, 'A', 60, 60, 0, 0, 0, 50, -60, 'H', 100, 'V', 100, 'L', 20, 30, 'C', 10, 20, 30, 40, 50, 60 ])
expect(path.node.getAttribute('d')).toBe('M50 60A60 60 0 0 0 50 -60H100V100L20 30C10 20 30 40 50 60 ')
})
})
describe('length()', function() {
it('gets the total length of the path', function() {
expect(path.length()).toBe(path.node.getTotalLength())
})
})
describe('pointAt()', function() {
it('gets a point at given length', function() {
expect(path.pointAt(100)).toEqual(path.node.getPointAtLength(100))
})
})
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | 2 | describe('Pattern', function() {
var rect, pattern
beforeEach(function() {
rect = draw.rect(100,100)
pattern = draw.pattern(20, 30, function(add) {
add.rect(10,10).move(10,10)
add.circle(30)
})
})
afterEach(function() {
rect.remove()
pattern.remove()
})
it('is an instance of SVG.Pattern', function() {
expect(pattern instanceof SVG.Pattern).toBe(true)
})
it('allows creation of a new gradient without block', function() {
pattern = draw.pattern(10,30)
expect(pattern.children().length).toBe(0)
})
describe('fill()', function() {
it('returns the id of the pattern wrapped in url()', function() {
expect(pattern.fill()).toBe('url(#' + pattern.attr('id') + ')')
})
})
describe('attr()', function() {
it('will catch transform attribues and convert them to patternTransform', function() {
expect(pattern.translate(100,100).attr('patternTransform')).toBe('matrix(1,0,0,1,100,100)')
})
})
describe('toString()', function() {
it('returns the id of the pattern wrapped in url()', function() {
expect(pattern + '').toBe('url(#' + pattern.attr('id') + ')')
})
it('is called when instance is passed as an attribute value', function() {
rect.attr('fill', pattern)
expect(rect.attr('fill')).toBe('url(#' + pattern.attr('id') + ')')
})
it('is called when instance is passed in a fill() method', function() {
rect.fill(pattern)
expect(rect.attr('fill')).toBe('url(#' + pattern.attr('id') + ')')
})
})
describe('update()', function() {
it('removes all existing children first', function() {
pattern = draw.pattern(30, 30, function(add) {
add.rect(10,10).move(10,10)
add.circle(30)
})
expect(pattern.children().length).toBe(2)
pattern.update(function(add) {
add.rect(10,10).move(10,10)
add.circle(30)
})
expect(pattern.children().length).toBe(2)
})
})
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 | 2 | describe('Point', function() {
var point
describe('initialization', function() {
describe('without a source', function() {
beforeEach(function() {
point = new SVG.Point
})
it('creates a new point with default values', function() {
expect(point.x).toBe(0)
expect(point.y).toBe(0)
})
})
describe('with x and y given', function() {
it('creates a point with given values', function() {
var point = new SVG.Point(2,4)
expect(point.x).toBe(2)
expect(point.y).toBe(4)
})
})
describe('with only x given', function() {
it('creates a point using the given value for both x and y', function() {
var point = new SVG.Point(7)
expect(point.x).toBe(7)
expect(point.y).toBe(7)
})
})
describe('with array given', function() {
it('creates a point from array', function() {
var point = new SVG.Point([2,4])
expect(point.x).toBe(2)
expect(point.y).toBe(4)
})
})
describe('with object given', function() {
it('creates a point from object', function() {
var point = new SVG.Point({x:2,y:4})
expect(point.x).toBe(2)
expect(point.y).toBe(4)
})
})
describe('with SVG.Point given', function() {
it('creates a point from SVG.Point', function() {
var point = new SVG.Point(new SVG.Point(2,4))
expect(point.x).toBe(2)
expect(point.y).toBe(4)
})
})
describe('with native SVGPoint given', function() {
it('creates a point from native SVGPoint', function() {
var point = new SVG.Point(new SVG.Point(2,4).native())
expect(point.x).toBe(2)
expect(point.y).toBe(4)
})
})
})
describe('clone()', function() {
it('returns cloned point', function() {
var point1 = new SVG.Point(1,1)
, point2 = point1.clone()
expect(point1).toEqual(point2)
expect(point1).not.toBe(point2)
})
})
describe('morph()', function() {
it('stores a given point for morphing', function() {
var point1 = new SVG.Point(1,1)
, point2 = new SVG.Point(2,2)
point1.morph(point2)
expect(point1.destination).toEqual(point2)
})
it('stores a clone, not the given matrix itself', function() {
var point1 = new SVG.Point(1,1)
, point2 = new SVG.Point(2,2)
point1.morph(point2)
expect(point1.destination).not.toBe(point2)
})
it('allow passing the point by directly passing its coordinates', function() {
var point1 = new SVG.Point(1,1)
, point2 = new SVG.Point(2,2)
point1.morph(point2.x, point2.y)
expect(point1.destination).toEqual(point2)
})
})
describe('at()', function() {
it('returns a morphed point at a given position', function() {
var point1 = new SVG.Point(1,1)
, point2 = new SVG.Point(2,2)
, point3 = point1.morph(point2).at(0.5)
expect(point3).toEqual(new SVG.Point(1.5, 1.5))
})
it('returns itself when no destination specified', function() {
var point = new SVG.Point(1,1)
expect(point.at(0.4)).toBe(point)
})
})
describe('transform()', function() {
it('returns a point transformed with given matrix', function() {
var point = new SVG.Point(1,5)
, matrix = new SVG.Matrix(0,0,1,0,0,1)
expect(point.transform(matrix)).toEqual(new SVG.Point(5,1))
})
})
describe('native()', function() {
it('returns native SVGPoint', function() {
expect(new SVG.Point().native() instanceof window.SVGPoint).toBeTruthy()
})
})
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 | 2 | describe('Polygon', function() {
var polygon
beforeEach(function() {
polygon = draw.polygon('0,0 100,0 100,100 0,100')
})
afterEach(function() {
draw.clear()
})
describe('()', function(){
it('falls back to a single point without an argument', function() {
polygon = draw.polygon()
expect(polygon.attr('points')).toBe('0,0')
})
})
describe('array()', function() {
it('returns an instance of SVG.PointArray', function() {
expect(polygon.array() instanceof SVG.PointArray).toBeTruthy()
})
it('returns the value stored in the private variable _array', function() {
expect(polygon.array()).toBe(polygon._array)
})
})
describe('x()', function() {
it('returns the value of x without an argument', function() {
expect(polygon.x()).toBe(0)
})
it('sets the value of x with the first argument', function() {
polygon.x(123)
var box = polygon.bbox()
expect(box.x).toBe(123)
})
})
describe('y()', function() {
it('returns the value of y without an argument', function() {
expect(polygon.y()).toBe(0)
})
it('sets the value of y with the first argument', function() {
polygon.y(345)
var box = polygon.bbox()
expect(box.y).toBe(345)
})
})
describe('cx()', function() {
it('returns the value of cx without an argument', function() {
expect(polygon.cx()).toBe(50)
})
it('sets the value of cx with the first argument', function() {
polygon.cx(123)
var box = polygon.bbox()
expect(box.cx).toBe(123)
})
})
describe('cy()', function() {
it('returns the value of cy without an argument', function() {
expect(polygon.cy()).toBe(50)
})
it('sets the value of cy with the first argument', function() {
polygon.cy(345)
var box = polygon.bbox()
expect(box.cy).toBe(345)
})
})
describe('move()', function() {
it('sets the x and y position', function() {
polygon.move(123,456)
var box = polygon.bbox()
expect(box.x).toBe(123)
expect(box.y).toBe(456)
})
})
describe('dx()', function() {
it('moves the x positon of the element relative to the current position', function() {
polygon.move(50,60)
polygon.dx(100)
var box = polygon.bbox()
expect(box.x).toBe(150)
})
})
describe('dy()', function() {
it('moves the y positon of the element relative to the current position', function() {
polygon.move(50, 60)
polygon.dy(120)
var box = polygon.bbox()
expect(box.y).toBe(180)
})
})
describe('dmove()', function() {
it('moves the x and y positon of the element relative to the current position', function() {
polygon.move(50,60)
polygon.dmove(80, 25)
var box = polygon.bbox()
expect(box.x).toBe(130)
expect(box.y).toBe(85)
})
})
describe('center()', function() {
it('sets the cx and cy position', function() {
polygon.center(321,567)
var box = polygon.bbox()
expect(box.x).toBe(271)
expect(box.y).toBe(517)
})
})
describe('width()', function() {
it('sets the width and height of the element', function() {
polygon.width(987)
var box = polygon.bbox()
expect(box.width).toBeCloseTo(987)
})
it('gets the width and height of the element without an argument', function() {
polygon.width(789)
expect(polygon.width()).toBeCloseTo(789)
})
})
describe('height()', function() {
it('sets the height and height of the element', function() {
polygon.height(987)
var box = polygon.bbox()
expect(box.height).toBeCloseTo(987)
})
it('gets the height and height of the element without an argument', function() {
polygon.height(789)
expect(polygon.height()).toBeCloseTo(789)
})
})
describe('size()', function() {
it('should define the width and height of the element', function() {
polygon.size(987,654)
var box = polygon.bbox()
expect(box.width).toBeCloseTo(987)
expect(box.height).toBeCloseTo(654)
})
it('defines the width and height proportionally with only the width value given', function() {
var box = polygon.bbox()
polygon.size(500)
expect(polygon.width()).toBe(500)
expect(polygon.width() / polygon.height()).toBe(box.width / box.height)
})
it('defines the width and height proportionally with only the height value given', function() {
var box = polygon.bbox()
polygon.size(null, 525)
expect(polygon.height()).toBe(525)
expect(polygon.width() / polygon.height()).toBe(box.width / box.height)
})
})
describe('scale()', function() {
it('should scale the element universally with one argument', function() {
var box1 = polygon.rbox()
, box2 = polygon.scale(2).rbox()
expect(box2.width).toBe(box1.width * 2)
expect(box2.height).toBe(box1.height * 2)
})
it('should scale the element over individual x and y axes with two arguments', function() {
var box1 = polygon.rbox()
, box2 = polygon.scale(2, 3.5).rbox()
expect(box2.width).toBe(box1.width * 2)
expect(box2.height).toBe(box1.height * 3.5)
})
})
describe('translate()', function() {
it('sets the translation of an element', function() {
polygon.transform({ x: 12, y: 12 })
expect(polygon.node.getAttribute('transform')).toBe('matrix(1,0,0,1,12,12)')
})
})
describe('plot()', function() {
it('changes the points attribute of the underlying polygon node when a string is passed', function() {
var pointString = '100,50 75,20 200,100'
, pointArray = new SVG.PointArray(pointString)
expect(polygon.plot(pointString)).toBe(polygon)
expect(polygon.attr('points')).toBe(pointArray.toString())
})
it('returns the point array when no arguments are passed', function () {
expect(polygon.plot()).toBe(polygon.array())
})
it('clears the array cache when a value is passed', function() {
polygon = draw.polygon([100,50,75,20,200,100])
expect(polygon._array instanceof SVG.PointArray).toBeTruthy()
polygon.plot('100,50 75,20 200,100')
expect(polygon._array).toBeUndefined()
})
it('applies a given polygon string value as is', function() {
var polyString = '100,50,75,20,200,100'
polygon = draw.polygon(polyString)
expect(polygon.attr('points')).toBe(polyString)
})
it('does not parse and cache a given string value to SVG.PointArray', function() {
polygon = draw.polygon('100,50 75,20 200,100')
expect(polygon._array).toBeUndefined()
})
it('caches a given array value', function() {
polygon = draw.polygon([100,50,75,20,200,100])
expect(polygon._array instanceof SVG.PointArray).toBeTruthy()
})
})
describe('clear()', function() {
it('clears the cached SVG.PointArray instance', function() {
polygon = draw.polygon([100,50,75,20,200,100])
polygon.clear()
expect(polygon._array).toBeUndefined()
})
})
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 | 2 | describe('Polyline', function() {
var polyline
beforeEach(function() {
polyline = draw.polyline('0,0 100,0 100,100 0,100')
})
afterEach(function() {
draw.clear()
})
describe('()', function(){
it('falls back to a single point without an argument', function() {
polyline = draw.polyline()
expect(polyline.attr('points')).toBe('0,0')
})
})
describe('array()', function() {
it('returns an instance of SVG.PointArray', function() {
expect(polyline.array() instanceof SVG.PointArray).toBeTruthy()
})
it('returns the value stored in the private variable _array', function() {
expect(polyline.array()).toBe(polyline._array)
})
})
describe('x()', function() {
it('returns the value of x without an argument', function() {
expect(polyline.x()).toBe(0)
})
it('sets the value of x with the first argument', function() {
polyline.x(123)
var box = polyline.bbox()
expect(box.x).toBe(123)
})
})
describe('y()', function() {
it('returns the value of y without an argument', function() {
expect(polyline.y()).toBe(0)
})
it('sets the value of y with the first argument', function() {
polyline.y(345)
var box = polyline.bbox()
expect(box.y).toBe(345)
})
})
describe('cx()', function() {
it('returns the value of cx without an argument', function() {
expect(polyline.cx()).toBe(50)
})
it('sets the value of cx with the first argument', function() {
polyline.cx(123)
var box = polyline.bbox()
expect(box.cx).toBe(123)
})
})
describe('cy()', function() {
it('returns the value of cy without an argument', function() {
expect(polyline.cy()).toBe(50)
})
it('sets the value of cy with the first argument', function() {
polyline.cy(345)
var box = polyline.bbox()
expect(box.cy).toBe(345)
})
})
describe('move()', function() {
it('sets the x and y position', function() {
polyline.move(123,456)
var box = polyline.bbox()
expect(box.x).toBe(123)
expect(box.y).toBe(456)
})
})
describe('dx()', function() {
it('moves the x positon of the element relative to the current position', function() {
polyline.move(50,60)
polyline.dx(100)
var box = polyline.bbox()
expect(box.x).toBe(150)
})
})
describe('dy()', function() {
it('moves the y positon of the element relative to the current position', function() {
polyline.move(50, 60)
polyline.dy(120)
var box = polyline.bbox()
expect(box.y).toBe(180)
})
})
describe('dmove()', function() {
it('moves the x and y positon of the element relative to the current position', function() {
polyline.move(50,60)
polyline.dmove(80, 25)
var box = polyline.bbox()
expect(box.x).toBe(130)
expect(box.y).toBe(85)
})
})
describe('center()', function() {
it('sets the cx and cy position', function() {
polyline.center(321,567)
var box = polyline.bbox()
expect(box.x).toBe(271)
expect(box.y).toBe(517)
})
})
describe('width()', function() {
it('sets the width and height of the element', function() {
polyline.width(987)
var box = polyline.bbox()
expect(box.width).toBeCloseTo(987, 1)
})
it('gets the width and height of the element without an argument', function() {
polyline.width(789)
expect(polyline.width()).toBeCloseTo(789)
})
})
describe('height()', function() {
it('sets the height and height of the element', function() {
polyline.height(987)
var box = polyline.bbox()
expect(box.height).toBeCloseTo(987)
})
it('gets the height and height of the element without an argument', function() {
polyline.height(789)
expect(polyline.height()).toBeCloseTo(789)
})
})
describe('size()', function() {
it('should define the width and height of the element', function() {
polyline.size(987,654)
var box = polyline.bbox()
expect(box.width).toBeCloseTo(987)
expect(box.height).toBeCloseTo(654)
})
it('defines the width and height proportionally with only the width value given', function() {
var box = polyline.bbox()
polyline.size(500)
expect(polyline.width()).toBe(500)
expect(polyline.width() / polyline.height()).toBe(box.width / box.height)
})
it('defines the width and height proportionally with only the height value given', function() {
var box = polyline.bbox()
polyline.size(null, 525)
expect(polyline.height()).toBe(525)
expect(polyline.width() / polyline.height()).toBe(box.width / box.height)
})
})
describe('scale()', function() {
it('should scale the element universally with one argument', function() {
var box1 = polyline.rbox()
, box2 = polyline.scale(2).rbox()
expect(box2.width).toBe(box1.width * 2)
expect(box2.height).toBe(box1.height * 2)
})
it('should scale the element over individual x and y axes with two arguments', function() {
var box1 = polyline.rbox()
, box2 = polyline.scale(2, 3.5).rbox()
expect(box2.width).toBe(box1.width * 2)
expect(box2.height).toBe(box1.height * 3.5)
})
})
describe('translate()', function() {
it('sets the translation of an element', function() {
polyline.transform({ x: 12, y: 12 })
expect(polyline.node.getAttribute('transform')).toBe('matrix(1,0,0,1,12,12)')
})
})
describe('plot()', function() {
it('change the points attribute of the underlying polyline node when a string is passed', function() {
var pointString = '100,50 75,20 200,100'
, pointArray = new SVG.PointArray(pointString)
expect(polyline.plot(pointString)).toBe(polyline)
expect(polyline.attr('points')).toBe(pointArray.toString())
})
it('return the point array when no arguments are passed', function () {
expect(polyline.plot()).toBe(polyline.array())
})
it('clears the array cache when a value is passed', function() {
polyline = draw.polyline([100,50,75,20,200,100])
expect(polyline._array instanceof SVG.PointArray).toBeTruthy()
polyline.plot('100,50 75,20 200,100')
expect(polyline._array).toBeUndefined()
})
it('applies a given polyline string value as is', function() {
var polyString = '100,50,75,20,200,100'
polyline = draw.polyline(polyString)
expect(polyline.attr('points')).toBe(polyString)
})
it('does not parse and cache a given string value to SVG.PointArray', function() {
polyline = draw.polyline('100,50 75,20 200,100')
expect(polyline._array).toBeUndefined()
})
it('caches a given array value', function() {
polyline = draw.polyline([100,50,75,20,200,100])
expect(polyline._array instanceof SVG.PointArray).toBeTruthy()
})
})
describe('clear()', function() {
it('clears the cached SVG.PointArray instance', function() {
polyline = draw.polyline([100,50,75,20,200,100])
polyline.clear()
expect(polyline._array).toBeUndefined()
})
})
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 | 2 | describe('Rect', function() {
var rect
beforeEach(function() {
rect = draw.rect(220,100)
})
afterEach(function() {
draw.clear()
})
describe('x()', function() {
it('should return the value of x without an argument', function() {
expect(rect.x()).toBe(0)
})
it('should set the value of x with the first argument', function() {
rect.x(123)
expect(rect.node.getAttribute('x')).toBe('123')
})
})
describe('y()', function() {
it('should return the value of y without an argument', function() {
expect(rect.y()).toBe(0)
})
it('should set the value of y with the first argument', function() {
rect.y(345)
expect(rect.node.getAttribute('y')).toBe('345')
})
})
describe('cx()', function() {
it('should return the value of cx without an argument', function() {
expect(rect.cx()).toBe(110)
})
it('should set the value of cx with the first argument', function() {
rect.cx(123)
var box = rect.bbox()
expect(box.cx).toBe(123)
})
})
describe('cy()', function() {
it('should return the value of cy without an argument', function() {
expect(rect.cy()).toBe(50)
})
it('should set the value of cy with the first argument', function() {
rect.cy(345)
var box = rect.bbox()
expect(box.cy).toBe(345)
})
})
describe('radius()', function() {
it('should set the rx and ry', function() {
rect.radius(10,20)
expect(rect.node.getAttribute('rx')).toBe('10')
expect(rect.node.getAttribute('ry')).toBe('20')
})
it('should set the rx and ry if only rx given', function() {
rect.radius(30)
expect(rect.node.getAttribute('rx')).toBe('30')
expect(rect.node.getAttribute('ry')).toBe('30')
})
})
describe('move()', function() {
it('should set the x and y position', function() {
rect.move(123,456)
expect(rect.node.getAttribute('x')).toBe('123')
expect(rect.node.getAttribute('y')).toBe('456')
})
})
describe('dx()', function() {
it('moves the x positon of the element relative to the current position', function() {
rect.move(50,60)
rect.dx(100)
expect(rect.node.getAttribute('x')).toBe('150')
})
})
describe('dy()', function() {
it('moves the y positon of the element relative to the current position', function() {
rect.move(50,60)
rect.dy(120)
expect(rect.node.getAttribute('y')).toBe('180')
})
})
describe('dmove()', function() {
it('moves the x and y positon of the element relative to the current position', function() {
rect.move(50,60)
rect.dmove(80, 25)
expect(rect.node.getAttribute('x')).toBe('130')
expect(rect.node.getAttribute('y')).toBe('85')
})
})
describe('center()', function() {
it('should set the cx and cy position', function() {
rect.center(321,567)
var box = rect.bbox()
expect(box.cx).toBe(321)
expect(box.cy).toBe(567)
})
})
describe('width()', function() {
it('sets the width of the element', function() {
rect.width(789)
expect(rect.node.getAttribute('width')).toBe('789')
})
it('gets the width of the element if the argument is null', function() {
expect(rect.width().toString()).toBe(rect.node.getAttribute('width'))
})
})
describe('height()', function() {
it('sets the height of the element', function() {
rect.height(1236)
expect(rect.node.getAttribute('height')).toBe('1236')
})
it('gets the height of the element if the argument is null', function() {
expect(rect.height().toString()).toBe(rect.node.getAttribute('height'))
})
})
describe('size()', function() {
it('should define the width and height of the element', function() {
rect.size(987,654)
expect(rect.node.getAttribute('width')).toBe('987')
expect(rect.node.getAttribute('height')).toBe('654')
})
it('defines the width and height proportionally with only the width value given', function() {
var box = rect.bbox()
rect.size(500)
expect(rect.width()).toBe(500)
expect(rect.width() / rect.height()).toBe(box.width / box.height)
})
it('defines the width and height proportionally with only the height value given', function() {
var box = rect.bbox()
rect.size(null, 525)
expect(rect.height()).toBe(525)
expect(rect.width() / rect.height()).toBe(box.width / box.height)
})
})
describe('scale()', function() {
it('should scale the element universally with one argument', function() {
var box = rect.scale(2).rbox()
expect(box.width).toBe(rect.attr('width') * 2)
expect(box.height).toBe(rect.attr('height') * 2)
})
it('should scale the element over individual x and y axes with two arguments', function() {
var box = rect.scale(2, 3.5).rbox()
expect(box.width).toBe(rect.attr('width') * 2)
expect(box.height).toBe(rect.attr('height') * 3.5)
})
})
describe('translate()', function() {
it('should set the translation of an element', function() {
rect.transform({ x: 12, y: 12 })
expect(rect.node.getAttribute('transform')).toBe('matrix(1,0,0,1,12,12)')
})
})
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 | 2 | describe('Regex', function() {
describe('matchers', function() {
describe('numberAndUnit', function() {
var match
it('is true with a positive unit value', function() {
match = ('10%').match(SVG.regex.numberAndUnit)
expect(match[1]).toBe('10')
expect(match[5]).toBe('%')
})
it('is true with a negative unit value', function() {
match = ('-11%').match(SVG.regex.numberAndUnit)
expect(match[1]).toBe('-11')
expect(match[5]).toBe('%')
})
it('is false with a positive unit value', function() {
match = ('NotAUnit').match(SVG.regex.numberAndUnit)
expect(match).toBeNull()
})
it('is true with a number', function() {
["1", "-1", "+15", "1.55", ".5", "5.", "1.3e2", "1E-4", "1e+12"].forEach(function(s) {
expect(SVG.regex.numberAndUnit.test(s)).toBeTruthy()
})
})
it('is false with a faulty number', function() {
["+-1", "1.2.3", "1+1", "1e4.5", ".5.", "1f5", "."].forEach(function(s) {
expect(SVG.regex.numberAndUnit.test(s)).toBeFalsy()
})
})
it('is true with a number with unit', function() {
["1px", "-1em", "+15%", "1.55s", ".5pt", "5.deg", "1.3e2rad", "1E-4grad", "1e+12cm"].forEach(function(s) {
expect(SVG.regex.numberAndUnit.test(s)).toBeTruthy()
})
})
it('is false with a faulty number or wrong unit', function() {
["1em1", "-1eq,5"].forEach(function(s) {
expect(SVG.regex.numberAndUnit.test(s)).toBeFalsy()
})
})
})
})
describe('testers', function() {
describe('isHex', function() {
it('is true with a three based hex', function() {
expect(SVG.regex.isHex.test('#f09')).toBeTruthy()
})
it('is true with a six based hex', function() {
expect(SVG.regex.isHex.test('#fe0198')).toBeTruthy()
})
it('is false with a faulty hex', function() {
expect(SVG.regex.isHex.test('###')).toBeFalsy()
expect(SVG.regex.isHex.test('#0')).toBeFalsy()
expect(SVG.regex.isHex.test('f06')).toBeFalsy()
})
})
describe('isRgb', function() {
it('is true with an rgb value', function() {
expect(SVG.regex.isRgb.test('rgb(255,66,100)')).toBeTruthy()
})
it('is false with a non-rgb value', function() {
expect(SVG.regex.isRgb.test('hsb(255, 100, 100)')).toBeFalsy()
})
})
describe('isNumber', function() {
it('is true with a number', function() {
["1", "-1", "+15", "1.55", ".5", "5.", "1.3e2", "1E-4", "1e+12"].forEach(function(s) {
expect(SVG.regex.isNumber.test(s)).toBeTruthy()
})
})
it('is false with a faulty number', function() {
["1a", "+-1", "1.2.3", "1+1", "1e4.5", ".5.", "1f5", "."].forEach(function(s) {
expect(SVG.regex.isNumber.test(s)).toBeFalsy()
})
})
})
})
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | 2 | describe('Selector', function() {
describe('get()', function() {
it('gets an element\'s instance by id', function() {
var rect = draw.rect(111, 333)
expect(SVG.get(rect.attr('id'))).toBe(rect)
})
it('makes all the element\'s methods available', function() {
var element = draw.group()
, got = SVG.get(element.attr('id'))
expect(got.attr()).toEqual(element.attr())
})
it('gets a referenced element by attribute value', function() {
var rect = draw.defs().rect(100, 100)
, use = draw.use(rect)
, mark = draw.marker(10, 10)
, path = draw.path(svgPath).marker('end', mark)
expect(SVG.get(use.attr('href'))).toBe(rect)
expect(SVG.get(path.attr('marker-end'))).toBe(mark)
})
})
describe('select()', function() {
var e1, e2, e3, e4 ,e5
beforeEach(function() {
e1 = draw.rect(100, 100).addClass('selectable-element')
e2 = draw.rect(100, 100).addClass('unselectable-element')
e3 = draw.rect(100, 100).addClass('selectable-element')
e4 = draw.rect(100, 100).addClass('unselectable-element')
e5 = draw.rect(100, 100).addClass('selectable-element')
})
it('gets all elements with a given class name', function() {
expect(SVG.select('rect.selectable-element').valueOf()).toEqual([e1, e3, e5])
})
it('returns an instance of SVG.Set', function() {
expect(SVG.select('rect.selectable-element') instanceof SVG.Set).toBe(true)
})
})
describe('Parent#select()', function() {
it('gets all elements with a given class name inside a given element', function() {
var group = draw.group()
, e1 = draw.rect(100, 100).addClass('selectable-element')
, e2 = draw.rect(100, 100).addClass('unselectable-element')
, e3 = group.rect(100, 100).addClass('selectable-element')
, e4 = draw.rect(100, 100).addClass('unselectable-element')
, e5 = group.rect(100, 100).addClass('selectable-element')
expect(group.select('rect.selectable-element').valueOf()).toEqual([e3, e5])
})
})
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 | 2 | describe('Set', function() {
var set, e1, e2, e3, e4, e5
beforeEach(function() {
draw.attr('viewBox', null)
set = draw.set()
e1 = draw.rect(100,100).attr('id', 'e1').move(200,250)
e2 = draw.ellipse(100,100).attr('id', 'e2')
e3 = draw.line(0,0,100,100).attr('id', 'e3')
e4 = draw.circle(50).attr('id', 'e4')
e5 = draw.polyline('0,0 10,20 30,50 80,100').attr('id', 'e5')
})
afterEach(function() {
draw.clear()
})
it('creates the set method on SVG.Container instances', function() {
expect(draw.set() instanceof SVG.Set).toBeTruthy()
})
it('creates a set with initial value', function() {
var members = [1, 2, 4]
expect(draw.set(members).valueOf()).toBe(members)
})
describe('add()', function() {
it('returns the set instance', function() {
expect(set.add(e1)).toBe(set)
})
it('stores given element', function() {
set.add(e1).add(e2).add(e3)
expect(set.valueOf()).toEqual([e1,e2,e3])
expect(set.members.length).toBe(3)
})
it('accepts multiple elements at once', function() {
set.add(e1, e2, e3, e4, e5)
expect(set.valueOf()).toEqual([e1, e2, e3, e4, e5])
expect(set.members.length).toBe(5)
})
})
describe('remove()', function() {
it('returns the set instance', function() {
set.add(e1)
expect(set.remove(e1)).toBe(set)
})
it('removes given element', function() {
set.add(e1).add(e2).add(e3).remove(e2)
expect(set.valueOf()).toEqual([e1,e3])
expect(set.members.length).toBe(2)
})
})
describe('each()', function() {
it('returns the set instance', function() {
expect(set.each(function(){})).toBe(set)
})
it('iterates over all members of the set', function() {
var ids = []
set.add(e1).add(e2).add(e3)
set.each(function() {
ids.push(this.attr('id'))
})
expect(ids.length).toBe(3)
expect(ids).toEqual(['e1','e2','e3'])
})
})
describe('clear()', function() {
it('returns the set instance', function() {
expect(set.clear()).toBe(set)
})
it('removes all members from set', function() {
set.add(e1).add(e2).add(e3).add(e4).add(e5).clear()
expect(set.members.length).toBe(0)
})
})
describe('get()', function() {
it('returns member at given index', function() {
set.add(e1).add(e2).add(e3).add(e4).add(e5)
expect(set.get(2)).toBe(e3)
})
})
describe('first()', function() {
it('returns first member', function() {
set.add(e1).add(e2).add(e3).add(e4).add(e5)
expect(set.first()).toBe(e1)
})
})
describe('last()', function() {
it('returns last member', function() {
set.add(e1).add(e2).add(e3).add(e4).add(e5)
expect(set.last()).toBe(e5)
})
})
describe('has()', function() {
it('checks if a given element is present in set', function() {
set.add(e1).add(e2).add(e3).add(e4).add(e5)
expect(set.has(e4)).toBeTruthy()
})
})
describe('length()', function() {
it('gets the length of the set', function() {
set.add(e1).add(e2).add(e3).add(e4).add(e5)
expect(set.length()).toBe(5)
})
})
describe('index()', function() {
it('returns the index of a given element within the set', function() {
set.add(e1).add(e2).add(e3).add(e5)
expect(set.index(e1)).toBe(0)
expect(set.index(e2)).toBe(1)
expect(set.index(e3)).toBe(2)
expect(set.index(e4)).toBe(-1)
expect(set.index(e5)).toBe(3)
})
})
describe('valueOf()', function() {
it('returns the members array', function() {
set.add(e1)
expect(set.valueOf()).toBe(set.members)
})
})
describe('bbox()', function() {
it('returns the bounding box of all elements', function() {
set.add(e1).add(e2).add(e3).add(e4).add(e5)
var box = set.bbox()
expect(box.x).toBeCloseTo(0)
expect(box.y).toBeCloseTo(0, 0)
expect(box.width).toBeCloseTo(300)
expect(box.height).toBeCloseTo(350)
})
it('returns an instance of SVG.RBox', function() {
set.add(e1).add(e2).add(e3).add(e4).add(e5)
expect(set.bbox() instanceof SVG.RBox).toBeTruthy()
})
it('returns an empty bounding box wiht no members', function() {
var box = set.bbox()
expect(box.x).toBe(0)
expect(box.y).toBe(0)
expect(box.width).toBe(0)
expect(box.height).toBe(0)
})
})
describe('method alias', function() {
describe('attr()', function() {
it('is applied to every member of the set', function() {
var fills = []
set.add(e1).add(e2).add(e3).add(e4).add(e5).attr('fill', '#ff0099')
set.each(function() {
fills.push(this.attr('fill'))
})
expect(fills).toEqual(['#ff0099','#ff0099','#ff0099','#ff0099','#ff0099'])
})
})
})
describe('method inheritance', function() {
beforeEach(function() {
SVG.extend(SVG.Element, {
orange: function() {
this.fill('#ff6600')
}
})
})
it('inherits newly added element methods after initialisation', function() {
expect(typeof set.orange).toBe('function')
})
it('applies newly inherited methods properly to members', function() {
var fills = []
set.add(e1).add(e2).add(e3).add(e4).add(e5).orange()
set.each(function() {
fills.push(this.attr('fill'))
})
expect(fills).toEqual(['#ff6600','#ff6600','#ff6600','#ff6600','#ff6600'])
})
})
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 | 2 | describe('Sugar', function() {
var rect
beforeEach(function() {
draw.attr('viewBox', null)
})
afterEach(function() {
draw.clear()
})
describe('fill()', function() {
beforeEach(function() {
rect = draw.rect(100,100)
})
afterEach(function() {
rect.remove()
})
it('returns the node reference', function() {
expect(rect.fill('red')).toBe(rect)
})
it('sets the given value', function() {
expect(rect.fill('red').attr('fill')).toBe('red')
})
it('sets the given value with object given', function() {
rect.fill({color: 'red', opacity: 0.5, rule: 'odd'})
expect(rect.attr('fill')).toBe('red')
expect(rect.attr('fill-opacity')).toBe(0.5)
expect(rect.attr('fill-rule')).toBe('odd')
})
it('is a nop with no argument given and returns node reference', function() {
rect.fill('red')
expect(rect.fill()).toBe(rect)
expect(rect.attr('fill')).toBe('red')
})
})
describe('rotate()', function() {
var rect, spy, undefined
beforeEach(function() {
rect = draw.rect(100,100)
spyOn(rect, 'transform')
})
afterEach(function() {
rect.remove()
rect.transform.calls.reset()
})
it('redirects to transform()', function() {
rect.rotate(1,2,3)
expect(rect.transform).toHaveBeenCalledWith({ rotation: 1, cx: 2, cy: 3 })
})
})
describe('skew()', function() {
var rect, spy, undefined
beforeEach(function() {
rect = draw.rect(100,100)
spyOn(rect, 'transform')
})
afterEach(function() {
rect.remove()
rect.transform.calls.reset()
})
it('redirects to transform() with no argument', function() {
rect.skew()
expect(rect.transform).toHaveBeenCalledWith({ skewX: undefined, skewY: undefined, cx: undefined, cy: undefined })
})
it('redirects to transform() with one argument', function() {
rect.skew(5)
expect(rect.transform).toHaveBeenCalledWith({ skew: 5, cx: undefined, cy: undefined })
})
it('redirects to transform() with two argument', function() {
rect.skew(5, 6)
expect(rect.transform).toHaveBeenCalledWith({ skewX: 5, skewY: 6, cx: undefined, cy: undefined })
})
it('redirects to transform() with three arguments', function() {
rect.skew(5, 6, 7)
expect(rect.transform).toHaveBeenCalledWith({ skew: 5, cx: 6, cy: 7 })
})
it('redirects to transform() with four arguments', function() {
rect.skew(5, 6, 7, 8)
expect(rect.transform).toHaveBeenCalledWith({ skewX: 5, skewY: 6, cx: 7, cy: 8 })
})
})
describe('scale()', function() {
var rect, spy, undefined
beforeEach(function() {
rect = draw.rect(100,100)
spyOn(rect, 'transform')
})
afterEach(function() {
rect.remove()
rect.transform.calls.reset()
})
it('redirects to transform() with no argument', function() {
rect.scale()
expect(rect.transform).toHaveBeenCalledWith({ scaleX: undefined, scaleY: undefined, cx: undefined, cy: undefined })
})
it('redirects to transform() with one argument', function() {
rect.scale(5)
expect(rect.transform).toHaveBeenCalledWith({ scale: 5, cx: undefined, cy: undefined })
})
it('redirects to transform() with two argument', function() {
rect.scale(5, 6)
expect(rect.transform).toHaveBeenCalledWith({ scaleX: 5, scaleY: 6, cx: undefined, cy: undefined })
})
it('redirects to transform() with three arguments', function() {
rect.scale(5, 6, 7)
expect(rect.transform).toHaveBeenCalledWith({ scale: 5, cx: 6, cy: 7 })
})
it('redirects to transform() with four arguments', function() {
rect.scale(5, 6, 7, 8)
expect(rect.transform).toHaveBeenCalledWith({ scaleX: 5, scaleY: 6, cx: 7, cy: 8 })
})
})
describe('translate()', function() {
var rect, spy, undefined
beforeEach(function() {
rect = draw.rect(100,100)
spyOn(rect, 'transform')
})
afterEach(function() {
rect.remove()
rect.transform.calls.reset()
})
it('redirects to transform()', function() {
rect.translate(1,2)
expect(rect.transform).toHaveBeenCalledWith({ x: 1, y: 2 })
})
})
describe('flip()', function() {
var rect, spy, undefined
beforeEach(function() {
rect = draw.rect(100,100)
spyOn(rect, 'transform')
})
afterEach(function() {
rect.remove()
rect.transform.calls.reset()
})
it('redirects to transform()', function() {
rect.flip('x',2)
expect(rect.transform).toHaveBeenCalledWith({ flip: 'x', offset: 2 })
})
it('sets flip to "both" when calling without anything', function() {
rect.flip()
expect(rect.transform).toHaveBeenCalledWith({ flip: 'both', offset: undefined })
})
// this works because only x and y are valid flip values. Evereything else flips on both axis
it('sets flip to number and offset to number when called with offset only', function() {
rect.flip(5)
expect(rect.transform).toHaveBeenCalledWith({ flip: 5, offset: 5 })
})
})
describe('matrix()', function() {
var rect, spy, undefined
beforeEach(function() {
rect = draw.rect(100,100)
spyOn(rect, 'attr')
})
afterEach(function() {
rect.remove()
rect.attr.calls.reset()
})
it('redirects to attr() directly with one argument', function() {
rect.matrix([1,2,3,4,5,6])
expect(rect.attr).toHaveBeenCalledWith('transform', new SVG.Matrix([1,2,3,4,5,6]))
})
it('redirects to attr() directly with 6 arguments', function() {
rect.matrix(1,2,3,4,5,6)
expect(rect.attr).toHaveBeenCalledWith('transform', new SVG.Matrix([1,2,3,4,5,6]))
})
})
describe('opacity()', function() {
var rect, spy, undefined
beforeEach(function() {
rect = draw.rect(100,100)
spyOn(rect, 'attr')
})
afterEach(function() {
rect.remove()
rect.attr.calls.reset()
})
it('redirects to attr() directly', function() {
rect.opacity(0.5)
expect(rect.attr).toHaveBeenCalledWith('opacity', 0.5)
})
})
describe('dx() / dy()', function() {
var rect, spy, undefined
beforeEach(function() {
rect = draw.rect(100,100)
spyOn(rect, 'x').and.callThrough()
spyOn(rect, 'y').and.callThrough()
})
afterEach(function() {
rect.remove()
rect.x.calls.reset()
rect.y.calls.reset()
})
it('redirects to x() / y() with adding the current value', function() {
rect.dx(5)
rect.dy(5)
expect(rect.x).toHaveBeenCalledWith(jasmine.objectContaining(new SVG.Number('5')), true)
expect(rect.y).toHaveBeenCalledWith(jasmine.objectContaining(new SVG.Number('5')), true)
})
it('allows to add a percentage value', function() {
rect.move('5%', '5%')
rect.dx('5%')
rect.dy('5%')
expect(rect.x).toHaveBeenCalledWith(jasmine.objectContaining(new SVG.Number('10%')), true)
expect(rect.y).toHaveBeenCalledWith(jasmine.objectContaining(new SVG.Number('10%')), true)
})
it('allows to add a percentage value when no x/y is set', function() {
rect.dx('5%')
rect.dy('5%')
expect(rect.x).toHaveBeenCalledWith(jasmine.objectContaining(new SVG.Number('5%')), true)
expect(rect.y).toHaveBeenCalledWith(jasmine.objectContaining(new SVG.Number('5%')), true)
})
})
describe('dmove()', function() {
var rect, spy, undefined
beforeEach(function() {
rect = draw.rect(100,100)
spyOn(rect, 'dx').and.callThrough()
spyOn(rect, 'dy').and.callThrough()
})
afterEach(function() {
rect.remove()
rect.dx.calls.reset()
rect.dy.calls.reset()
})
it('redirects to dx() / dy() directly', function() {
rect.dmove(5,5)
expect(rect.dx).toHaveBeenCalledWith(5)
expect(rect.dy).toHaveBeenCalledWith(5)
})
})
describe('font()', function() {
var text, spy, undefined
beforeEach(function() {
text = draw.text(loremIpsum)
spyOn(text, 'leading')
spyOn(text, 'attr')
})
afterEach(function() {
text.remove()
text.leading.calls.reset()
text.attr.calls.reset()
})
it('sets leading when given', function() {
text.font({leading: 3})
expect(text.leading).toHaveBeenCalledWith(3)
})
it('sets text-anchor when anchor given', function() {
text.font({anchor: 'start'})
expect(text.attr).toHaveBeenCalledWith('text-anchor', 'start')
})
it('sets all font properties via attr()', function() {
text.font({
size: 20,
family: 'Verdana',
weight: 'bold',
stretch: 'wider',
variant: 'small-caps',
style: 'italic'
})
expect(text.attr).toHaveBeenCalledWith('font-size', 20)
expect(text.attr).toHaveBeenCalledWith('font-family', 'Verdana')
expect(text.attr).toHaveBeenCalledWith('font-weight', 'bold')
expect(text.attr).toHaveBeenCalledWith('font-stretch', 'wider')
expect(text.attr).toHaveBeenCalledWith('font-variant', 'small-caps')
expect(text.attr).toHaveBeenCalledWith('font-style', 'italic')
})
it('redirects all other stuff directly to attr()', function() {
text.font({
foo:'bar',
bar:'baz'
})
expect(text.attr).toHaveBeenCalledWith('foo', 'bar')
expect(text.attr).toHaveBeenCalledWith('bar', 'baz')
})
it('sets key value pair when called with 2 parameters', function() {
text.font('size', 20)
expect(text.attr).toHaveBeenCalledWith('font-size', 20)
})
it('gets value if called with one parameter', function() {
text.font('size')
expect(text.attr).toHaveBeenCalledWith('font-size', undefined)
})
})
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 | 2 | describe('SVG', function() {
describe('()', function() {
var drawing, wrapper
beforeEach(function() {
wrapper = document.createElement('svg')
document.documentElement.appendChild(wrapper)
drawing = SVG(wrapper)
})
afterEach(function() {
wrapper.parentNode.removeChild(wrapper)
})
it('creates a new svg drawing', function() {
expect(drawing.type).toBe('svg')
})
it('creates an instance of SVG.Doc', function() {
expect(drawing instanceof SVG.Doc).toBe(true)
})
if(parserInDoc){
it('sets no default size in svg documents', function() {
expect(drawing.width()).toBe(0)
expect(drawing.height()).toBe(0)
})
}else{
it('sets size to 100% in html documents', function() {
expect(drawing.width()).toBe('100%')
expect(drawing.height()).toBe('100%')
})
}
})
describe('create()', function() {
it('creates an element with given node name and return it', function() {
var element = SVG.create('rect')
expect(element.nodeName).toBe('rect')
})
it('increases the global id sequence', function() {
var did = SVG.did
, element = SVG.create('rect')
expect(did + 1).toBe(SVG.did)
})
it('adds a unique id containing the node name', function() {
var did = SVG.did
, element = SVG.create('rect')
expect(element.getAttribute('id')).toBe('SvgjsRect' + did)
})
})
describe('extend()', function() {
it('adds all functions in the given object to the target object', function() {
SVG.extend(SVG.Rect, {
soft: function() {
return this.opacity(0.2)
}
})
expect(typeof SVG.Rect.prototype.soft).toBe('function')
expect(draw.rect(100,100).soft().attr('opacity')).toBe(0.2)
})
it('accepts and extend multiple modules at once', function() {
SVG.extend(SVG.Rect, SVG.Ellipse, SVG.Path, {
soft: function() {
return this.opacity(0.5)
}
})
expect(typeof SVG.Rect.prototype.soft).toBe('function')
expect(draw.rect(100,100).soft().attr('opacity')).toBe(0.5)
expect(typeof SVG.Ellipse.prototype.soft).toBe('function')
expect(draw.ellipse(100,100).soft().attr('opacity')).toBe(0.5)
expect(typeof SVG.Path.prototype.soft).toBe('function')
expect(draw.path().soft().attr('opacity')).toBe(0.5)
})
it('ignores non existant objects', function() {
SVG.extend(SVG.Rect, SVG.Bogus, {
soft: function() {
return this.opacity(0.3)
}
})
expect(typeof SVG.Rect.prototype.soft).toBe('function')
expect(draw.rect(100,100).soft().attr('opacity')).toBe(0.3)
expect(typeof SVG.Bogus).toBe('undefined')
})
})
describe('prepare()', function() {
var drawing, wrapper, parser
beforeEach(function() {
wrapper = document.createElement('svg')
document.documentElement.appendChild(wrapper)
drawing = SVG(wrapper)
})
it('creates a parser element when calling SVG()', function() {
expect(SVG.parser.draw.nodeName).toBe('svg')
})
it('hides the parser', function() {
expect(window.stripped(SVG.parser.draw.getAttribute('style'))).toBe('overflow:hidden;top:-100%;left:-100%;position:absolute;opacity:0')
})
it('holds polyline and path', function() {
expect(SVG.select('polyline', SVG.parser.draw).first().type).toBe('polyline')
expect(SVG.select('path', SVG.parser.draw).first().type).toBe('path')
})
})
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 2 | describe('Symbol', function() {
describe('()', function() {
var element
beforeEach(function() {
element = draw.symbol()
})
it('creates an instance of SVG.Symbol', function() {
expect(element instanceof SVG.Symbol).toBeTruthy()
})
it('is an instance of SVG.Container', function() {
expect(element instanceof SVG.Container).toBeTruthy()
})
})
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 | 2 | // IMPORTANT!!!
// The native getBBox() on text elements isn't always accurate in the decimals.
// Therefore sometimes some rounding is used to make test work as expected.
describe('Text', function() {
var text
beforeEach(function() {
text = draw.text(loremIpsum).size(5)
})
afterEach(function() {
draw.clear()
})
describe('leading()', function() {
it('returns the leading value of the text without an argument', function() {
expect(text.leading() instanceof SVG.Number)
expect(text.leading().valueOf()).toBe(1.3)
})
it('sets the leading value of the text with the first argument', function() {
expect(text.leading(1.5).dom.leading.valueOf()).toBe(1.5)
})
})
describe('rebuild()', function() {
it('disables the rebuild if called with false', function() {
expect(text.rebuild(false)._rebuild).toBeFalsy()
})
it('enables the rebuild if called with true', function() {
expect(text.rebuild(true)._rebuild).toBeTruthy()
})
it('rebuilds the text without an argument given', function() {
var dy = text.lines().get(2).attr('dy')
text.leading(1.7)
expect(dy == text.lines().get(2).attr('dy')).toBeFalsy()
})
})
describe('x()', function() {
it('returns the value of x without an argument', function() {
expect(text.x()).toBe(0)
})
it('sets the value of x with the first argument', function() {
text.x(123)
expect(text.node.getAttribute('x')).toBeCloseTo(123)
})
it('sets the value of all lines', function() {
text.x(200)
text.lines().each(function() {
expect(this.x()).toBe(200)
})
})
it('sets the value of y with a percent value', function() {
text.x('40%')
expect(text.node.getAttribute('x')).toBe('40%')
})
it('returns the value of x when x is a percentual value', function() {
expect(text.x('45%').x()).toBe('45%')
})
// Woow this test is old. The functionality not even implemented anymore
// Was a good feature. Maybe we add it back?
/*it('sets the value of x based on the anchor with the first argument', function() {
text.x(123, true)
var box = text.bbox()
expect(box.x).toBeCloseTo(123)
})*/
})
describe('y()', function() {
it('returns the value of y without an argument', function() {
expect(text.y(0).y()).toBeCloseTo(0)
})
it('returns the value of y when y is a percentual value', function() {
expect(text.y('45%').y()).toBe('45%')
})
it('sets the value of y with the first argument', function() {
text.y(345)
var box = text.bbox()
expect(box.y).toBe(345)
})
it('sets the value of y with a percent value', function() {
text.y('40%')
expect(text.node.getAttribute('y')).toBe('40%')
})
})
describe('cx()', function() {
it('returns the value of cx without an argument', function() {
var box = text.bbox()
expect(text.cx()).toBeCloseTo(box.x + box.width / 2)
})
it('sets the value of cx with the first argument', function() {
text.cx(123)
var box = text.bbox()
// this is a hack. it should be exactly 123 since you set it. But bbox with text is a thing...
expect(box.cx).toBeCloseTo(box.x + box.width/2)
})
// not implemented anymore
/*it('sets the value of cx based on the anchor with the first argument', function() {
text.cx(123, true)
var box = text.bbox()
expect(box.cx).toBeCloseTo(123)
})*/
})
describe('cy()', function() {
it('returns the value of cy without an argument', function() {
var box = text.bbox()
expect(text.cy()).toBe(box.cy)
})
it('sets the value of cy with the first argument', function() {
text.cy(345)
var box = text.bbox()
expect(Math.round(box.cy * 10) / 10).toBe(345)
})
})
describe('move()', function() {
it('sets the x and y position', function() {
text.move(123,456)
expect(text.node.getAttribute('x')).toBe('123')
expect(text.y()).toBeCloseTo(456)
})
})
describe('center()', function() {
it('sets the cx and cy position', function() {
text.center(321, 567)
var box = text.bbox()
expect(+text.node.getAttribute('x') + box.width / 2).toBeCloseTo(321, 1)
expect(text.y() + box.height / 2).toBeCloseTo(567)
})
})
describe('size()', function() {
it('should define the width and height of the element', function() {
text.size(50)
expect(text.attr('font-size').valueOf()).toBe(50)
})
})
describe('translate()', function() {
it('sets the translation of an element', function() {
text.transform({ x: 12, y: 12 })
expect(text.node.getAttribute('transform')).toBe('matrix(1,0,0,1,12,12)')
})
})
describe('text()', function() {
it('adds content in a nested tspan', function() {
text.text('It is a bear!')
expect(text.node.childNodes[0].nodeType).toBe(1)
expect(text.node.childNodes[0].childNodes[0].data).toBe('It is a bear!')
})
it('adds content in a nested tspan even with an empty string', function() {
text.text('')
expect(text.node.childNodes[0].nodeType).toBe(1)
expect(text.node.childNodes[0].childNodes[0].data).toBe('')
})
it('creates multiple lines with a newline separated string', function() {
text.text('It is\nJUST\na bear!')
expect(text.node.childNodes.length).toBe(3)
})
it('restores the content from the dom', function() {
text.text('It is\nJUST\na bear!')
expect(text.text()).toBe('It is\nJUST\na bear!')
})
it('gets the given content of a text element without an argument', function() {
text.text('It is another bear!')
expect(text.node.childNodes[0].nodeType).toBe(1)
expect(text.text()).toMatch('It is another bear!')
})
it('accepts a block as first arguments', function() {
text.text(function(add) {
add.tspan('mastaba')
add.plain('hut')
})
expect(text.node.childNodes[0].nodeType).toBe(1)
expect(text.node.childNodes[0].childNodes[0].data).toBe('mastaba')
expect(text.node.childNodes[1].nodeType).toBe(3)
expect(text.node.childNodes[1].data).toBe('hut')
})
})
describe('plain()', function() {
it('adds content without a tspan', function() {
text.plain('It is a bear!')
expect(text.node.childNodes[0].nodeType).toBe(3)
expect(text.node.childNodes[0].data).toBe('It is a bear!')
})
it('clears content before adding new content', function() {
text.plain('It is not a bear!')
expect(text.node.childNodes.length).toBe(1)
expect(text.node.childNodes[0].data).toBe('It is not a bear!')
})
it('restores the content from the dom', function() {
text.plain('Just plain text!')
expect(text.text()).toBe('Just plain text!')
})
})
describe('tspan()', function() {
it('adds content in a tspan', function() {
text.tspan('It is a bear!')
expect(text.node.childNodes[0].nodeType).toBe(1)
expect(text.node.childNodes[0].childNodes[0].data).toBe('It is a bear!')
})
it('clears content before adding new content', function() {
text.tspan('It is not a bear!')
expect(text.node.childNodes.length).toBe(1)
expect(text.node.childNodes[0].childNodes[0].data).toBe('It is not a bear!')
})
})
describe('clear()', function() {
it('removes all content', function() {
text.text(function(add) {
add.tspan('The first.')
add.tspan('The second.')
add.tspan('The third.')
})
expect(text.node.childNodes.length).toBe(3)
text.clear()
expect(text.node.childNodes.length).toBe(0)
})
})
describe('lines()', function() {
it('gets an array of individual lines as an instance of SVG.Set', function() {
var l1, l2, l3
text.text(function(add) {
l1 = add.tspan('The first.')
l2 = add.tspan('The second.')
l3 = add.tspan('The third.')
})
expect(text.lines().length()).toBe(3)
expect(text.lines().get(0)).toBe(l1)
expect(text.lines().get(1)).toBe(l2)
expect(text.lines().get(2)).toBe(l3)
})
})
describe('length()', function() {
it('gets total length of text', function() {
text.text(function(add) {
add.tspan('The first.')
add.tspan('The second.')
add.tspan('The third.')
})
expect(text.length()).toBeCloseTo(text.lines().get(0).length() + text.lines().get(1).length() + text.lines().get(2).length(), 3)
})
})
describe('build()', function() {
it('enables adding multiple plain text nodes when given true', function() {
text.clear().build(true)
text.plain('A great piece!')
text.plain('Another great piece!')
expect(text.node.childNodes[0].data).toBe('A great piece!')
expect(text.node.childNodes[1].data).toBe('Another great piece!')
})
it('enables adding multiple tspan nodes when given true', function() {
text.clear().build(true)
text.tspan('A great piece!')
text.tspan('Another great piece!')
expect(text.node.childNodes[0].childNodes[0].data).toBe('A great piece!')
expect(text.node.childNodes[1].childNodes[0].data).toBe('Another great piece!')
})
it('disables adding multiple plain text nodes when given false', function() {
text.clear().build(true)
text.plain('A great piece!')
text.build(false).plain('Another great piece!')
expect(text.node.childNodes[0].data).toBe('Another great piece!')
expect(text.node.childNodes[1]).toBe(undefined)
})
it('disables adding multiple tspan nodes when given false', function() {
text.clear().build(true)
text.tspan('A great piece!')
text.build(false).tspan('Another great piece!')
expect(text.node.childNodes[0].childNodes[0].data).toBe('Another great piece!')
expect(text.node.childNodes[1]).toBe(undefined)
})
})
describe('setData()', function() {
it('read all data from the svgjs:data attribute and assign it to el.dom', function(){
text.attr('svgjs:data', '{"foo":"bar","leading":"3px"}')
text.setData(JSON.parse(text.attr('svgjs:data')))
expect(text.dom.foo).toBe('bar')
expect(text.dom.leading instanceof SVG.Number).toBeTruthy()
expect(text.dom.leading.value).toBe(3)
expect(text.dom.leading.unit).toBe('px')
})
})
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | 2 | describe('TextPath', function() {
var text
, data = 'M 100 200 C 200 100 300 0 400 100 C 500 200 600 300 700 200 C 800 100 900 100 900 100'
beforeEach(function() {
text = draw.text('We go up, then we go down, then up again')
})
afterEach(function() {
draw.clear()
})
describe('path()', function() {
it('returns the text element', function() {
expect(text.path(data)).toBe(text)
})
it('creates a textPath node in the text element', function() {
text.path(data)
expect(text.node.firstChild.nodeName).toBe('textPath')
})
})
describe('textPath()', function() {
it('creates a reference to the textPath', function() {
expect(text.path(data).textPath() instanceof SVG.TextPath).toBe(true)
})
})
describe('track()', function() {
it('creates a reference to the path', function() {
expect(text.path(data).track() instanceof SVG.Path).toBe(true)
})
})
describe('array()', function() {
it('return the path array of the underlying path', function() {
expect(text.path(data).array()).toEqual(new SVG.PathArray(data))
})
it('return null if there is no underlying path', function () {
expect(text.array()).toBe(null)
})
})
describe('plot()', function() {
it('change the array of the underlying path when a string is passed', function() {
expect(text.path().plot(data)).toBe(text)
expect(text.array()).toEqual(new SVG.PathArray(data))
})
it('do nothing when a string is passed and there is no underlying path', function() {
expect(text.plot(data)).toBe(text)
expect(text.array()).toEqual(null)
})
it('return the path array of the underlying path when no arguments is passed', function () {
text.path(data)
expect(text.plot()).toBe(text.array())
expect(text.plot()).not.toBe(null)
})
it('return null when no arguments is passed and there is no underlying path', function () {
expect(text.plot()).toBe(null)
})
})
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 | 2 | describe('Transformations:', function() {
var translated, scaled, rotated, skewed
beforeEach(function() {
translated = draw.rect(100,100).translate(100,100)
scaled = draw.rect(100,100).scale(2)
rotated = draw.rect(100,100).rotate(45, 50, 50)
skewed = draw.rect(100,100).skew(30)
})
/* SVG.Transformation is not tested because it is an abstract prototype */
describe('SVG.Transformation', function() {
it('marks the transformation as inversed when inverse flag given', function() {
var trans = new SVG.Transformation([], true)
expect(trans.inversed).toBeTruthy()
})
})
describe('SVG.Translate', function() {
var trans
beforeEach(function(){
trans = new SVG.Translate(translated.transform())
})
it('creates an object of type SVG.Transformation', function() {
expect(trans instanceof SVG.Transformation).toBeTruthy()
})
it('uses transformedX and transformedY as arguments', function() {
expect(trans.arguments).toEqual(['transformedX', 'transformedY'])
})
it('s method is translate()', function() {
expect(trans.method).toEqual('translate')
})
it('sets the necessary parameters at creation', function() {
expect(trans.transformedX).toBe(100)
expect(trans.transformedY).toBe(100)
})
describe('undo', function() {
it('sets the undo matrix which can undo the translation', function() {
var extracted = (new SVG.Matrix(1,0,0,1,20,20)).extract()
trans.undo(extracted)
expect(trans._undo.toString()).toEqual('matrix(1,0,0,1,-20,-20)')
var extracted = (new SVG.Matrix(10,0,0,10,20,20)).extract()
trans.undo(extracted)
expect(trans._undo.toString()).toEqual('matrix(1,0,0,1,-2,-2)')
var extracted = (new SVG.Matrix(10,50,50,30,20,20)).extract()
trans.undo(extracted)
expect(trans._undo.e).toBeCloseTo(-extracted.transformedX)
expect(trans._undo.f).toBeCloseTo(-extracted.transformedY)
})
})
describe('at', function() {
it('creates a matrix at a certain position', function() {
expect(trans.at(0.3).toString()).toEqual('matrix(1,0,0,1,30,30)')
})
it('returns the inversed matrix from a specific position when created with inverse flag', function() {
expect((new SVG.Translate(translated.transform(), true)).at(0.3).toString()).toEqual('matrix(1,0,0,1,-30,-30)')
})
it('returns the resulting transformation which has to be made to set an absolute translation', function() {
trans.undo(new SVG.Matrix(10,50,50,30,20,20).extract())
expect(trans.at(0.4).a).toEqual(1)
expect(trans.at(0.4).b).toEqual(0)
expect(trans.at(0.4).c).toEqual(0)
expect(trans.at(0.4).d).toEqual(1)
expect(trans.at(0.4).e).toBeCloseTo(100 * 0.4 + trans._undo.e * 0.4)
expect(trans.at(0.4).f).toBeCloseTo(100 * 0.4 + trans._undo.f * 0.4)
})
})
})
describe('SVG.Rotate', function() {
var trans
beforeEach(function(){
trans = new SVG.Rotate(45, 50, 50)
})
it('creates an object of type SVG.Transformation', function() {
expect(trans instanceof SVG.Transformation).toBeTruthy()
})
it('uses rotation, cx and cy as arguments', function() {
expect(trans.arguments).toEqual(['rotation', 'cx', 'cy'])
})
it('s method is rotate()', function() {
expect(trans.method).toEqual('rotate')
})
it('sets the necessary parameters at creation', function() {
expect(trans.rotation).toBe(45)
expect(trans.cx).toBe(50)
expect(trans.cy).toBe(50)
})
describe('undo', function() {
it('sets an undo object which holds rotation', function() {
var extracted = (new SVG.Matrix(1,0,0,1,0,0)).rotate(20, 50, 50).extract()
trans.undo(extracted)
expect(trans._undo.rotation).toBeCloseTo(20)
})
})
describe('at', function() {
it('creates a matrix at a certain position', function() {
expect(trans.at(0.3).toString()).toEqual((new SVG.Matrix()).rotate(0.3 * 45, 50, 50).toString())
})
it('returns the resulting transformation which has to be made to set an absolute translation', function() {
trans.undo((new SVG.Matrix()).rotate(20, 50, 50).extract())
expect(trans.at(0.4).a).toBeCloseTo(1,1)
expect(trans.at(0.4).b).toEqual(jasmine.any(Number))
expect(trans.at(0.4).c).toEqual(jasmine.any(Number))
expect(trans.at(0.4).d).toBeCloseTo(1,1)
expect(trans.at(0.4).e).toEqual(jasmine.any(Number))
expect(trans.at(0.4).f).toEqual(jasmine.any(Number))
})
})
})
describe('SVG.Scale', function() {
var trans
beforeEach(function(){
trans = new SVG.Scale(2,2,50,50)
})
it('creates an object of type SVG.Transformation', function() {
expect(trans instanceof SVG.Transformation).toBeTruthy()
})
it('uses scaleX, scaleY, cx and cy as arguments', function() {
expect(trans.arguments).toEqual(['scaleX', 'scaleY', 'cx', 'cy'])
})
it('s method is scale()', function() {
expect(trans.method).toEqual('scale')
})
it('sets the necessary parameters at creation', function() {
expect(trans.scaleX).toBe(2)
expect(trans.scaleY).toBe(2)
expect(trans.cx).toBe(50)
expect(trans.cy).toBe(50)
})
describe('undo', function() {
it('sets the undo matrix which can undo the translation', function() {
var extracted = (new SVG.Matrix(4,0,0,4,0,0)).extract()
trans.undo(extracted)
expect(trans._undo.toString()).toEqual('matrix(0.25,0,0,0.25,37.5,37.5)')
var extracted = (new SVG.Matrix(10,0,0,10,20,20)).extract()
trans.undo(extracted)
expect(trans._undo.a).toBeCloseTo(1/extracted.scaleX)
expect(trans._undo.d).toBeCloseTo(1/extracted.scaleY)
expect(trans._undo.e).toBeCloseTo(45)
expect(trans._undo.f).toBeCloseTo(45)
var extracted = (new SVG.Matrix(10,50,50,30,20,20)).extract()
trans.undo(extracted)
expect(trans._undo.a).toBeCloseTo(1/extracted.scaleX)
expect(trans._undo.d).toBeCloseTo(1/extracted.scaleY)
})
})
describe('at', function() {
it('creates a matrix at a certain position', function() {
expect(trans.at(0.75).toString()).toEqual('matrix(1.75,0,0,1.75,-37.5,-37.5)')
})
it('returns the inversed matrix from a specific position when created with inverse flag', function() {
var morphed = (new SVG.Scale(scaled.transform(2,2,50,50), true)).at(0.25)
expect(morphed.a).toBeCloseTo(0.8)
expect(morphed.d).toBeCloseTo(0.8)
})
it('returns the resulting transformation which has to be made to set an absolute translation', function() {
var morphed = trans.undo((new SVG.Matrix(10,0,0,10,0,0)).extract()).at(0.5)
expect(morphed.a).toBeCloseTo(0.6)
expect(morphed.b).toEqual(0)
expect(morphed.c).toEqual(0)
expect(morphed.d).toBeCloseTo(0.6)
expect(morphed.e).toBeCloseTo(20)
expect(morphed.f).toBeCloseTo(20)
})
})
})
describe('SVG.Skew', function() {
var trans
beforeEach(function(){
trans = new SVG.Skew(30,-30,50,50)
})
it('creates an object of type SVG.Transformation', function() {
expect(trans instanceof SVG.Transformation).toBeTruthy()
})
it('uses scaleX, scaleY, cx and cy as arguments', function() {
expect(trans.arguments).toEqual(['skewX', 'skewY', 'cx', 'cy'])
})
it('s method is skew()', function() {
expect(trans.method).toEqual('skew')
})
it('sets the necessary parameters at creation', function() {
expect(trans.skewX).toBe(30)
expect(trans.skewY).toBe(-30)
expect(trans.cx).toBe(50)
expect(trans.cy).toBe(50)
})
describe('undo', function() {
it('sets the undo matrix which can undo the translation', function() {
var extracted = (new SVG.Matrix()).skew(90, 90, 0, 0).extract()
trans.undo(extracted)
expect(trans._undo.a).toBeCloseTo(0)
expect(trans._undo.b).toBeCloseTo(0)
expect(trans._undo.c).toBeCloseTo(0)
expect(trans._undo.d).toBeCloseTo(0)
expect(trans._undo.e).toBeCloseTo(50)
expect(trans._undo.f).toBeCloseTo(50)
var extracted = (new SVG.Matrix(10,0,0,10,20,20)).extract()
trans.undo(extracted)
expect(trans._undo.a).toBeCloseTo(1)
expect(trans._undo.b).toBeCloseTo(0)
expect(trans._undo.c).toBeCloseTo(0)
expect(trans._undo.d).toBeCloseTo(1)
expect(trans._undo.e).toBeCloseTo(0)
expect(trans._undo.f).toBeCloseTo(0)
})
})
describe('at', function() {
it('creates a matrix at a certain position', function() {
expect(trans.at(0.75)).toEqual((new SVG.Matrix()).morph((new SVG.Matrix()).skew(30, -30, 50, 50)).at(0.75))
})
it('returns the inversed matrix from a specific position when created with inverse flag', function() {
var morphed = (new SVG.Scale(skewed.transform(20,-20,50,50), true)).at(0.25)
expect(morphed.a).toBeCloseTo(0.963)
expect(morphed.b).toBeCloseTo(0)
expect(morphed.c).toBeCloseTo(0)
expect(morphed.d).toBeCloseTo(0.963)
expect(morphed.e).toBeCloseTo(0)
expect(morphed.f).toBeCloseTo(0)
})
it('returns the resulting transformation which has to be made to set an absolute translation', function() {
var morphed = trans.undo((new SVG.Matrix(10,0,0,10,0,0)).skew(20, 30, 20, 10).extract()).at(0.5)
expect(morphed.a).toBeCloseTo(1.266)
expect(morphed.b).toBeCloseTo(-0.7310)
expect(morphed.c).toBeCloseTo(0.1351)
expect(morphed.d).toBeCloseTo(0.9220)
expect(morphed.e).toBeCloseTo(-20.05593)
expect(morphed.f).toBeCloseTo(40.4468)
})
})
})
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | 2 | describe('Tspan', function() {
var text, tspan
beforeEach(function() {
text = draw.text(loremIpsum)
tspan = text.tspan('Hello World')
})
afterEach(function() {
draw.clear()
})
describe('newLine()', function() {
it('converts the tspan to a line', function() {
tspan = text.tspan('Hello World')
expect(tspan.newLine().dom.newLined).toBeTruthy()
})
})
describe('text()', function() {
it('returns the text of the tspan without newline when not newlined', function() {
tspan = text.tspan('Hello World')
expect(tspan.text()).toBe('Hello World')
})
it('returns the text of the tspan with newline when newlined', function() {
tspan = text.tspan('Hello World').newLine()
expect(tspan.text()).toBe('Hello World\n')
})
it('calls the function when function given', function() {
var spy = jasmine.createSpy('dummy')
tspan = text.tspan('Hello World')
tspan.text(spy)
expect(spy).toHaveBeenCalledWith(tspan)
})
})
describe('dx()', function() {
it('gets the dx value with no argument', function() {
tspan.attr('dx', 25)
expect(tspan.dx()).toBe(25)
})
it('sets the dx value whith the first argument', function() {
expect(tspan.dx(25).attr('dx')).toBe(25)
})
})
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | 2 | describe('Use', function() {
var use
describe('on a container element', function() {
var rect
beforeEach(function() {
rect = draw.rect(100,100)
use = draw.use(rect)
})
it('creates an instance of SVG.Use', function() {
expect(use instanceof SVG.Use).toBe(true)
})
it('sets the target element id to its href attribute', function() {
expect(use.node.getAttributeNS(SVG.xlink, 'href')).toBe('#' + rect)
})
it('adopts the geometry of the target element', function() {
expect(use.bbox()).toEqual(rect.bbox())
})
})
describe('on an external path', function() {
var file = 'http://upload.wikimedia.org/wikipedia/commons/8/84/Example.svg'
, id = 'flowRoot1882'
beforeEach(function() {
use = draw.use(id, file)
})
it('creates an instance of SVG.Use', function() {
expect(use instanceof SVG.Use).toBe(true)
})
it('sets the target element id and file path to its href attribute', function() {
expect(use.node.getAttributeNS(SVG.xlink, 'href')).toBe(file + '#' + id)
})
})
})
|
| 1 2 3 4 5 6 7 8 9 10 11 | 2 | describe('SVG.utils', function() {
describe('degrees()', function() {
it('converts radiant to degrees', function() {
expect(SVG.utils.degrees(Math.PI)).toBe(180)
})
it('maps to 0 - 360 degree only', function() {
expect(SVG.utils.degrees(2.5 * Math.PI)).toBe(90)
})
})
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 | 2 | describe('Viewbox', function() {
var viewbox
beforeEach(function() {
draw.clear()
})
describe('initialization', function() {
it('creates a new viewbox with default values', function() {
viewbox = new SVG.ViewBox()
expect(viewbox.x).toBe(0)
expect(viewbox.y).toBe(0)
expect(viewbox.width).toBe(0)
expect(viewbox.height).toBe(0)
})
it('creates a new viewbox from parsed string', function() {
viewbox = new SVG.ViewBox('10. 100 200 300')
expect(viewbox.x).toBe(10)
expect(viewbox.y).toBe(100)
expect(viewbox.width).toBe(200)
expect(viewbox.height).toBe(300)
})
it('creates a new viewbox from array', function() {
viewbox = new SVG.ViewBox([10, 100, 200, 300])
expect(viewbox.x).toBe(10)
expect(viewbox.y).toBe(100)
expect(viewbox.width).toBe(200)
expect(viewbox.height).toBe(300)
})
it('creates a new viewbox from object', function() {
viewbox = new SVG.ViewBox({x:10, y:100, width:200, height:300})
expect(viewbox.x).toBe(10)
expect(viewbox.y).toBe(100)
expect(viewbox.width).toBe(200)
expect(viewbox.height).toBe(300)
})
it('creates a new viewbox from 4 arguments given', function() {
viewbox = new SVG.ViewBox(10, 100, 200, 300)
expect(viewbox.x).toBe(10)
expect(viewbox.y).toBe(100)
expect(viewbox.width).toBe(200)
expect(viewbox.height).toBe(300)
})
it('creates a new viewbox from parsed string with exponential values', function() {
viewbox = new SVG.ViewBox('-1.12e1 1e-2 +2e2 +.3e+4')
expect(viewbox.x).toBe(-11.2)
expect(viewbox.y).toBe(0.01)
expect(viewbox.width).toBe(200)
expect(viewbox.height).toBe(3000)
})
it('creates a new viewbox with element given', function() {
draw.attr('viewBox', '-1.12e1 1e-2 +2e2 +.3e+4')
viewbox = new SVG.ViewBox(draw)
expect(viewbox.x).toBe(-11.2)
expect(viewbox.y).toBe(0.01)
expect(viewbox.width).toBe(200)
expect(viewbox.height).toBe(3000)
})
})
describe('viewbox()', function() {
beforeEach(function() {
draw.attr('viewBox', null)
})
afterEach(function() {
draw.attr('viewBox', null)
})
it('should set the viewbox when four arguments are provided', function() {
draw.viewbox(0,0,100,100)
expect(draw.node.getAttribute('viewBox')).toBe('0 0 100 100')
})
it('should set the viewbox when an object is provided as first argument', function() {
draw.viewbox({ x: 0, y: 0, width: 50, height: 50 })
expect(draw.node.getAttribute('viewBox')).toBe('0 0 50 50')
})
it('should set the viewbox when a string is provided as first argument', function() {
draw.viewbox('0 0 50 50')
expect(draw.node.getAttribute('viewBox')).toBe('0 0 50 50')
})
it('should set the viewbox when an array is provided as first argument', function() {
draw.viewbox([0, 0, 50, 50])
expect(draw.node.getAttribute('viewBox')).toBe('0 0 50 50')
})
it('should accept negative values', function() {
draw.size(100,100).viewbox(-100, -100, 50, 50)
expect(draw.node.getAttribute('viewBox')).toEqual('-100 -100 50 50')
})
it('should get the viewbox if no arguments are given', function() {
draw.viewbox(0, 0, 100, 100)
expect(draw.viewbox()).toEqual(new SVG.ViewBox(draw))
})
it('should define the zoom of the viewbox in relation to the canvas size', function() {
draw.size(100,100).viewbox(0,0,50,50)
expect(draw.viewbox().zoom).toEqual(100 / 50)
})
})
describe('morph()', function() {
it('stores a given viewbox for morphing', function() {
var viewbox1 = new SVG.ViewBox(10, 100, 200, 300)
, viewbox2 = new SVG.ViewBox(50, -100, 300, 300)
viewbox1.morph(viewbox2)
expect(viewbox1.destination).toEqual(viewbox2)
})
it('stores a clone, not the given viewbox itself', function() {
var viewbox1 = new SVG.ViewBox(10, 100, 200, 300)
, viewbox2 = new SVG.ViewBox(50, -100, 300, 300)
viewbox1.morph(viewbox2)
expect(viewbox1.destination).not.toBe(viewbox2)
})
})
describe('at()', function() {
it('returns a morphed viewbox at a given position', function() {
var viewbox1 = new SVG.ViewBox(10, 100, 200, 300)
, viewbox2 = new SVG.ViewBox(50, -100, 300, 300)
, viewbox3 = viewbox1.morph(viewbox2).at(0.5)
expect(viewbox1.toString()).toBe('10 100 200 300')
expect(viewbox2.toString()).toBe('50 -100 300 300')
expect(viewbox3.toString()).toBe('30 0 250 300')
})
it('returns itself when no destination given', function() {
var viewbox = new SVG.ViewBox(10, 100, 200, 300)
expect(viewbox.at(0.5)).toBe(viewbox)
})
})
})
|
| File | Statements | Branches | Functions | Lines | |||||
|---|---|---|---|---|---|---|---|---|---|
| arrange.js | 3.33% | (1 / 30) | 0% | (0 / 8) | 0% | (0 / 10) | 3.33% | (1 / 30) | |
| array.js | 2.86% | (1 / 35) | 0% | (0 / 14) | 0% | (0 / 10) | 3.03% | (1 / 33) | |
| attr.js | 2.63% | (1 / 38) | 0% | (0 / 45) | 0% | (0 / 2) | 2.7% | (1 / 37) | |
| bare.js | 8.33% | (1 / 12) | 0% | (0 / 4) | 0% | (0 / 3) | 8.33% | (1 / 12) | |
| boxes.js | 1.52% | (1 / 66) | 0% | (0 / 24) | 0% | (0 / 10) | 1.59% | (1 / 63) | |
| clip.js | 6.25% | (1 / 16) | 0% | (0 / 4) | 0% | (0 / 5) | 6.25% | (1 / 16) | |
| color.js | 2.5% | (1 / 40) | 0% | (0 / 24) | 0% | (0 / 10) | 2.63% | (1 / 38) | |
| container.js | 50% | (1 / 2) | 100% | (0 / 0) | 0% | (0 / 1) | 50% | (1 / 2) | |
| data.js | 10% | (1 / 10) | 0% | (0 / 11) | 0% | (0 / 1) | 10% | (1 / 10) | |
| default.js | 100% | (1 / 1) | 100% | (0 / 0) | 100% | (0 / 0) | 100% | (1 / 1) | |
| defs.js | 100% | (1 / 1) | 100% | (0 / 0) | 100% | (0 / 0) | 100% | (1 / 1) | |
| element.js | 1.08% | (1 / 93) | 0% | (0 / 52) | 0% | (0 / 38) | 1.14% | (1 / 88) | |
| ellipse.js | 5.26% | (1 / 19) | 0% | (0 / 12) | 0% | (0 / 13) | 5.26% | (1 / 19) | |
| event.js | 3.45% | (2 / 58) | 0% | (0 / 57) | 12.5% | (1 / 8) | 3.64% | (2 / 55) | |
| fx.js | 0.29% | (1 / 339) | 0% | (0 / 190) | 0% | (0 / 78) | 0.31% | (1 / 319) | |
| gradient.js | 3.45% | (1 / 29) | 0% | (0 / 22) | 0% | (0 / 11) | 4% | (1 / 25) | |
| group.js | 7.14% | (1 / 14) | 0% | (0 / 8) | 0% | (0 / 6) | 7.14% | (1 / 14) | |
| helpers.js | 20.93% | (18 / 86) | 0% | (0 / 42) | 0% | (0 / 18) | 21.18% | (18 / 85) | |
| hyperlink.js | 9.09% | (1 / 11) | 0% | (0 / 2) | 0% | (0 / 5) | 9.09% | (1 / 11) | |
| image.js | 4.35% | (1 / 23) | 0% | (0 / 22) | 0% | (0 / 6) | 4.76% | (1 / 21) | |
| line.js | 8.33% | (1 / 12) | 0% | (0 / 6) | 0% | (0 / 5) | 8.33% | (1 / 12) | |
| marker.js | 5.26% | (1 / 19) | 0% | (0 / 6) | 0% | (0 / 8) | 5.56% | (1 / 18) | |
| mask.js | 6.25% | (1 / 16) | 0% | (0 / 4) | 0% | (0 / 5) | 6.25% | (1 / 16) | |
| matrix.js | 1.96% | (1 / 51) | 0% | (0 / 44) | 0% | (0 / 19) | 2% | (1 / 50) | |
| memory.js | 7.14% | (1 / 14) | 0% | (0 / 8) | 0% | (0 / 3) | 7.14% | (1 / 14) | |
| nested.js | 25% | (1 / 4) | 100% | (0 / 0) | 0% | (0 / 2) | 25% | (1 / 4) | |
| number.js | 2.56% | (1 / 39) | 0% | (0 / 38) | 0% | (0 / 11) | 2.63% | (1 / 38) | |
| parent.js | 3.33% | (1 / 30) | 0% | (0 / 10) | 0% | (0 / 14) | 3.33% | (1 / 30) | |
| path.js | 7.69% | (1 / 13) | 0% | (0 / 16) | 0% | (0 / 10) | 7.69% | (1 / 13) | |
| patharray.js | 4.29% | (6 / 140) | 0% | (0 / 68) | 4.55% | (1 / 22) | 4.41% | (6 / 136) | |
| pattern.js | 7.69% | (1 / 13) | 0% | (0 / 4) | 0% | (0 / 6) | 8.33% | (1 / 12) | |
| point.js | 5.26% | (1 / 19) | 0% | (0 / 10) | 0% | (0 / 7) | 5.56% | (1 / 18) | |
| pointarray.js | 2.44% | (1 / 41) | 0% | (0 / 18) | 0% | (0 / 8) | 2.7% | (1 / 37) | |
| pointed.js | 14.29% | (1 / 7) | 0% | (0 / 8) | 0% | (0 / 4) | 14.29% | (1 / 7) | |
| poly.js | 8.33% | (1 / 12) | 0% | (0 / 10) | 0% | (0 / 7) | 8.33% | (1 / 12) | |
| polyfill.js | 4.55% | (1 / 22) | 0% | (0 / 12) | 0% | (0 / 4) | 4.55% | (1 / 22) | |
| rect.js | 50% | (1 / 2) | 100% | (0 / 0) | 0% | (0 / 1) | 50% | (1 / 2) | |
| regex.js | 100% | (1 / 1) | 100% | (0 / 0) | 100% | (0 / 0) | 100% | (1 / 1) | |
| selector.js | 12.5% | (1 / 8) | 0% | (0 / 4) | 0% | (0 / 4) | 12.5% | (1 / 8) | |
| set.js | 1.96% | (1 / 51) | 0% | (0 / 22) | 0% | (0 / 21) | 1.96% | (1 / 51) | |
| shape.js | 50% | (1 / 2) | 100% | (0 / 0) | 0% | (0 / 1) | 50% | (1 / 2) | |
| style.js | 6.25% | (1 / 16) | 0% | (0 / 14) | 0% | (0 / 3) | 6.67% | (1 / 15) | |
| sugar.js | 13.51% | (5 / 37) | 0% | (0 / 52) | 5.88% | (1 / 17) | 13.89% | (5 / 36) | |
| symbol.js | 50% | (1 / 2) | 100% | (0 / 0) | 0% | (0 / 1) | 50% | (1 / 2) | |
| text.js | 1.18% | (1 / 85) | 0% | (0 / 56) | 0% | (0 / 24) | 1.19% | (1 / 84) | |
| textpath.js | 5.56% | (1 / 18) | 0% | (0 / 12) | 0% | (0 / 5) | 5.56% | (1 / 18) | |
| transform.js | 0.74% | (1 / 136) | 0% | (0 / 137) | 0% | (0 / 18) | 0.77% | (1 / 130) | |
| ungroup.js | 7.14% | (1 / 14) | 0% | (0 / 17) | 0% | (0 / 3) | 9.09% | (1 / 11) | |
| use.js | 33.33% | (1 / 3) | 0% | (0 / 2) | 0% | (0 / 2) | 33.33% | (1 / 3) | |
| utilities.js | 7.14% | (1 / 14) | 0% | (0 / 2) | 0% | (0 / 6) | 7.69% | (1 / 13) | |
| viewbox.js | 2.08% | (1 / 48) | 0% | (0 / 24) | 0% | (0 / 6) | 2.13% | (1 / 47) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | 2 | // ### This module adds backward / forward functionality to elements.
//
SVG.extend(SVG.Element, {
// Get all siblings, including myself
siblings: function() {
return this.parent().children()
}
// Get the curent position siblings
, position: function() {
return this.parent().index(this)
}
// Get the next element (will return null if there is none)
, next: function() {
return this.siblings()[this.position() + 1]
}
// Get the next element (will return null if there is none)
, previous: function() {
return this.siblings()[this.position() - 1]
}
// Send given element one step forward
, forward: function() {
var i = this.position() + 1
, p = this.parent()
// move node one step forward
p.removeElement(this).add(this, i)
// make sure defs node is always at the top
if (p instanceof SVG.Doc)
p.node.appendChild(p.defs().node)
return this
}
// Send given element one step backward
, backward: function() {
var i = this.position()
if (i > 0)
this.parent().removeElement(this).add(this, i - 1)
return this
}
// Send given element all the way to the front
, front: function() {
var p = this.parent()
// Move node forward
p.node.appendChild(this.node)
// Make sure defs node is always at the top
if (p instanceof SVG.Doc)
p.node.appendChild(p.defs().node)
return this
}
// Send given element all the way to the back
, back: function() {
if (this.position() > 0)
this.parent().removeElement(this).add(this, 0)
return this
}
// Inserts a given element before the targeted element
, before: function(element) {
element.remove()
var i = this.position()
this.parent().add(element, i)
return this
}
// Insters a given element after the targeted element
, after: function(element) {
element.remove()
var i = this.position()
this.parent().add(element, i + 1)
return this
}
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | 2 | // Module for array conversion SVG.Array = function(array, fallback) { array = (array || []).valueOf() // if array is empty and fallback is provided, use fallback if (array.length == 0 && fallback) array = fallback.valueOf() // parse array this.value = this.parse(array) } SVG.extend(SVG.Array, { // Make array morphable morph: function(array) { this.destination = this.parse(array) // normalize length of arrays if (this.value.length != this.destination.length) { var lastValue = this.value[this.value.length - 1] , lastDestination = this.destination[this.destination.length - 1] while(this.value.length > this.destination.length) this.destination.push(lastDestination) while(this.value.length < this.destination.length) this.value.push(lastValue) } return this } // Clean up any duplicate points , settle: function() { // find all unique values for (var i = 0, il = this.value.length, seen = []; i < il; i++) if (seen.indexOf(this.value[i]) == -1) seen.push(this.value[i]) // set new value return this.value = seen } // Get morphed array at given position , at: function(pos) { // make sure a destination is defined if (!this.destination) return this // generate morphed array for (var i = 0, il = this.value.length, array = []; i < il; i++) array.push(this.value[i] + (this.destination[i] - this.value[i]) * pos) return new SVG.Array(array) } // Convert array to string , toString: function() { return this.value.join(' ') } // Real value , valueOf: function() { return this.value } // Parse whitespace separated string , parse: function(array) { array = array.valueOf() // if already is an array, no need to parse it if (Array.isArray(array)) return array return this.split(array) } // Strip unnecessary whitespace , split: function(string) { return string.trim().split(SVG.regex.delimiter).map(parseFloat) } // Reverse array , reverse: function() { this.value.reverse() return this } , clone: function() { var clone = new this.constructor() clone.value = array_clone(this.value) return clone } }) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | 2 | SVG.extend(SVG.Element, {
// Set svg element attribute
attr: function(a, v, n) {
// act as full getter
if (a == null) {
// get an object of attributes
a = {}
v = this.node.attributes
for (n = v.length - 1; n >= 0; n--)
a[v[n].nodeName] = SVG.regex.isNumber.test(v[n].nodeValue) ? parseFloat(v[n].nodeValue) : v[n].nodeValue
return a
} else if (typeof a == 'object') {
// apply every attribute individually if an object is passed
for (v in a) this.attr(v, a[v])
} else if (v === null) {
// remove value
this.node.removeAttribute(a)
} else if (v == null) {
// act as a getter if the first and only argument is not an object
v = this.node.getAttribute(a)
return v == null ?
SVG.defaults.attrs[a] :
SVG.regex.isNumber.test(v) ?
parseFloat(v) : v
} else {
// BUG FIX: some browsers will render a stroke if a color is given even though stroke width is 0
if (a == 'stroke-width')
this.attr('stroke', parseFloat(v) > 0 ? this._stroke : null)
else if (a == 'stroke')
this._stroke = v
// convert image fill and stroke to patterns
if (a == 'fill' || a == 'stroke') {
if (SVG.regex.isImage.test(v))
v = this.doc().defs().image(v, 0, 0)
if (v instanceof SVG.Image)
v = this.doc().defs().pattern(0, 0, function() {
this.add(v)
})
}
// ensure correct numeric values (also accepts NaN and Infinity)
if (typeof v === 'number')
v = new SVG.Number(v)
// ensure full hex color
else if (SVG.Color.isColor(v))
v = new SVG.Color(v)
// parse array values
else if (Array.isArray(v))
v = new SVG.Array(v)
// if the passed attribute is leading...
if (a == 'leading') {
// ... call the leading method instead
if (this.leading)
this.leading(v)
} else {
// set given attribute on node
typeof n === 'string' ?
this.node.setAttributeNS(n, a, v.toString()) :
this.node.setAttribute(a, v.toString())
}
// rebuild if required
if (this.rebuild && (a == 'font-size' || a == 'x'))
this.rebuild(a, v)
}
return this
}
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | 2 |
SVG.Bare = SVG.invent({
// Initialize
create: function(element, inherit) {
// construct element
this.constructor.call(this, SVG.create(element))
// inherit custom methods
if (inherit)
for (var method in inherit.prototype)
if (typeof inherit.prototype[method] === 'function')
this[method] = inherit.prototype[method]
}
// Inherit from
, inherit: SVG.Element
// Add methods
, extend: {
// Insert some plain text
words: function(text) {
// remove contents
while (this.node.hasChildNodes())
this.node.removeChild(this.node.lastChild)
// create text node
this.node.appendChild(document.createTextNode(text))
return this
}
}
})
SVG.extend(SVG.Parent, {
// Create an element that is not described by SVG.js
element: function(element, inherit) {
return this.put(new SVG.Bare(element, inherit))
}
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 | 2 | SVG.Box = SVG.invent({
create: function(x, y, width, height) {
if (typeof x == 'object' && !(x instanceof SVG.Element)) {
// chromes getBoundingClientRect has no x and y property
return SVG.Box.call(this, x.left != null ? x.left : x.x , x.top != null ? x.top : x.y, x.width, x.height)
} else if (arguments.length == 4) {
this.x = x
this.y = y
this.width = width
this.height = height
}
// add center, right, bottom...
fullBox(this)
}
, extend: {
// Merge rect box with another, return a new instance
merge: function(box) {
var b = new this.constructor()
// merge boxes
b.x = Math.min(this.x, box.x)
b.y = Math.min(this.y, box.y)
b.width = Math.max(this.x + this.width, box.x + box.width) - b.x
b.height = Math.max(this.y + this.height, box.y + box.height) - b.y
return fullBox(b)
}
, transform: function(m) {
var xMin = Infinity, xMax = -Infinity, yMin = Infinity, yMax = -Infinity, p, bbox
var pts = [
new SVG.Point(this.x, this.y),
new SVG.Point(this.x2, this.y),
new SVG.Point(this.x, this.y2),
new SVG.Point(this.x2, this.y2)
]
pts.forEach(function(p) {
p = p.transform(m)
xMin = Math.min(xMin,p.x)
xMax = Math.max(xMax,p.x)
yMin = Math.min(yMin,p.y)
yMax = Math.max(yMax,p.y)
})
bbox = new this.constructor()
bbox.x = xMin
bbox.width = xMax-xMin
bbox.y = yMin
bbox.height = yMax-yMin
fullBox(bbox)
return bbox
}
}
})
SVG.BBox = SVG.invent({
// Initialize
create: function(element) {
SVG.Box.apply(this, [].slice.call(arguments))
// get values if element is given
if (element instanceof SVG.Element) {
var box
// yes this is ugly, but Firefox can be a bitch when it comes to elements that are not yet rendered
try {
if (!document.documentElement.contains){
// This is IE - it does not support contains() for top-level SVGs
var topParent = element.node
while (topParent.parentNode){
topParent = topParent.parentNode
}
if (topParent != document) throw new Exception('Element not in the dom')
} else {
// the element is NOT in the dom, throw error
if(!document.documentElement.contains(element.node)) throw new Exception('Element not in the dom')
}
// find native bbox
box = element.node.getBBox()
} catch(e) {
if(element instanceof SVG.Shape){
var clone = element.clone(SVG.parser.draw.instance).show()
box = clone.node.getBBox()
clone.remove()
}else{
box = {
x: element.node.clientLeft
, y: element.node.clientTop
, width: element.node.clientWidth
, height: element.node.clientHeight
}
}
}
SVG.Box.call(this, box)
}
}
// Define ancestor
, inherit: SVG.Box
// Define Parent
, parent: SVG.Element
// Constructor
, construct: {
// Get bounding box
bbox: function() {
return new SVG.BBox(this)
}
}
})
SVG.BBox.prototype.constructor = SVG.BBox
SVG.extend(SVG.Element, {
tbox: function(){
console.warn('Use of TBox is deprecated and mapped to RBox. Use .rbox() instead.')
return this.rbox(this.doc())
}
})
SVG.RBox = SVG.invent({
// Initialize
create: function(element) {
SVG.Box.apply(this, [].slice.call(arguments))
if (element instanceof SVG.Element) {
SVG.Box.call(this, element.node.getBoundingClientRect())
}
}
, inherit: SVG.Box
// define Parent
, parent: SVG.Element
, extend: {
addOffset: function() {
// offset by window scroll position, because getBoundingClientRect changes when window is scrolled
this.x += window.pageXOffset
this.y += window.pageYOffset
return this
}
}
// Constructor
, construct: {
// Get rect box
rbox: function(el) {
if (el) return new SVG.RBox(this).transform(el.screenCTM().inverse())
return new SVG.RBox(this).addOffset()
}
}
})
SVG.RBox.prototype.constructor = SVG.RBox
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | 2 | SVG.ClipPath = SVG.invent({
// Initialize node
create: function() {
this.constructor.call(this, SVG.create('clipPath'))
// keep references to clipped elements
this.targets = []
}
// Inherit from
, inherit: SVG.Container
// Add class methods
, extend: {
// Unclip all clipped elements and remove itself
remove: function() {
// unclip all targets
for (var i = this.targets.length - 1; i >= 0; i--)
if (this.targets[i])
this.targets[i].unclip()
this.targets = []
// remove clipPath from parent
this.parent().removeElement(this)
return this
}
}
// Add parent method
, construct: {
// Create clipping element
clip: function() {
return this.defs().put(new SVG.ClipPath)
}
}
})
//
SVG.extend(SVG.Element, {
// Distribute clipPath to svg element
clipWith: function(element) {
// use given clip or create a new one
this.clipper = element instanceof SVG.ClipPath ? element : this.parent().clip().add(element)
// store reverence on self in mask
this.clipper.targets.push(this)
// apply mask
return this.attr('clip-path', 'url("#' + this.clipper.attr('id') + '")')
}
// Unclip element
, unclip: function() {
delete this.clipper
return this.attr('clip-path', null)
}
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 | 2 | // Module for color convertions SVG.Color = function(color) { var match // initialize defaults this.r = 0 this.g = 0 this.b = 0 if(!color) return // parse color if (typeof color === 'string') { if (SVG.regex.isRgb.test(color)) { // get rgb values match = SVG.regex.rgb.exec(color.replace(SVG.regex.whitespace,'')) // parse numeric values this.r = parseInt(match[1]) this.g = parseInt(match[2]) this.b = parseInt(match[3]) } else if (SVG.regex.isHex.test(color)) { // get hex values match = SVG.regex.hex.exec(fullHex(color)) // parse numeric values this.r = parseInt(match[1], 16) this.g = parseInt(match[2], 16) this.b = parseInt(match[3], 16) } } else if (typeof color === 'object') { this.r = color.r this.g = color.g this.b = color.b } } SVG.extend(SVG.Color, { // Default to hex conversion toString: function() { return this.toHex() } // Build hex value , toHex: function() { return '#' + compToHex(this.r) + compToHex(this.g) + compToHex(this.b) } // Build rgb value , toRgb: function() { return 'rgb(' + [this.r, this.g, this.b].join() + ')' } // Calculate true brightness , brightness: function() { return (this.r / 255 * 0.30) + (this.g / 255 * 0.59) + (this.b / 255 * 0.11) } // Make color morphable , morph: function(color) { this.destination = new SVG.Color(color) return this } // Get morphed color at given position , at: function(pos) { // make sure a destination is defined if (!this.destination) return this // normalise pos pos = pos < 0 ? 0 : pos > 1 ? 1 : pos // generate morphed color return new SVG.Color({ r: ~~(this.r + (this.destination.r - this.r) * pos) , g: ~~(this.g + (this.destination.g - this.g) * pos) , b: ~~(this.b + (this.destination.b - this.b) * pos) }) } }) // Testers // Test if given value is a color string SVG.Color.test = function(color) { color += '' return SVG.regex.isHex.test(color) || SVG.regex.isRgb.test(color) } // Test if given value is a rgb object SVG.Color.isRgb = function(color) { return color && typeof color.r == 'number' && typeof color.g == 'number' && typeof color.b == 'number' } // Test if given value is a color SVG.Color.isColor = function(color) { return SVG.Color.isRgb(color) || SVG.Color.test(color) } |
| 1 2 3 4 5 6 7 8 9 10 11 | 2 | SVG.Container = SVG.invent({
// Initialize node
create: function(element) {
this.constructor.call(this, element)
}
// Inherit from
, inherit: SVG.Parent
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | 2 |
SVG.extend(SVG.Element, {
// Store data values on svg nodes
data: function(a, v, r) {
if (typeof a == 'object') {
for (v in a)
this.data(v, a[v])
} else if (arguments.length < 2) {
try {
return JSON.parse(this.attr('data-' + a))
} catch(e) {
return this.attr('data-' + a)
}
} else {
this.attr(
'data-' + a
, v === null ?
null :
r === true || typeof v === 'string' || typeof v === 'number' ?
v :
JSON.stringify(v)
)
}
return this
}
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | 2 |
SVG.defaults = {
// Default attribute values
attrs: {
// fill and stroke
'fill-opacity': 1
, 'stroke-opacity': 1
, 'stroke-width': 0
, 'stroke-linejoin': 'miter'
, 'stroke-linecap': 'butt'
, fill: '#000000'
, stroke: '#000000'
, opacity: 1
// position
, x: 0
, y: 0
, cx: 0
, cy: 0
// size
, width: 0
, height: 0
// radius
, r: 0
, rx: 0
, ry: 0
// gradient
, offset: 0
, 'stop-opacity': 1
, 'stop-color': '#000000'
// text
, 'font-size': 16
, 'font-family': 'Helvetica, Arial, sans-serif'
, 'text-anchor': 'start'
}
}
|
| 1 2 3 4 5 6 7 8 9 10 | 2 |
SVG.Defs = SVG.invent({
// Initialize node
create: 'defs'
// Inherit from
, inherit: SVG.Container
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 | 2 |
SVG.Element = SVG.invent({
// Initialize node
create: function(node) {
// make stroke value accessible dynamically
this._stroke = SVG.defaults.attrs.stroke
this._event = null
// initialize data object
this.dom = {}
// create circular reference
if (this.node = node) {
this.type = node.nodeName
this.node.instance = this
// store current attribute value
this._stroke = node.getAttribute('stroke') || this._stroke
}
}
// Add class methods
, extend: {
// Move over x-axis
x: function(x) {
return this.attr('x', x)
}
// Move over y-axis
, y: function(y) {
return this.attr('y', y)
}
// Move by center over x-axis
, cx: function(x) {
return x == null ? this.x() + this.width() / 2 : this.x(x - this.width() / 2)
}
// Move by center over y-axis
, cy: function(y) {
return y == null ? this.y() + this.height() / 2 : this.y(y - this.height() / 2)
}
// Move element to given x and y values
, move: function(x, y) {
return this.x(x).y(y)
}
// Move element by its center
, center: function(x, y) {
return this.cx(x).cy(y)
}
// Set width of element
, width: function(width) {
return this.attr('width', width)
}
// Set height of element
, height: function(height) {
return this.attr('height', height)
}
// Set element size to given width and height
, size: function(width, height) {
var p = proportionalSize(this, width, height)
return this
.width(new SVG.Number(p.width))
.height(new SVG.Number(p.height))
}
// Clone element
, clone: function(parent, withData) {
// write dom data to the dom so the clone can pickup the data
this.writeDataToDom()
// clone element and assign new id
var clone = assignNewId(this.node.cloneNode(true))
// insert the clone in the given parent or after myself
if(parent) parent.add(clone)
else this.after(clone)
return clone
}
// Remove element
, remove: function() {
if (this.parent())
this.parent().removeElement(this)
return this
}
// Replace element
, replace: function(element) {
this.after(element).remove()
return element
}
// Add element to given container and return self
, addTo: function(parent) {
return parent.put(this)
}
// Add element to given container and return container
, putIn: function(parent) {
return parent.add(this)
}
// Get / set id
, id: function(id) {
return this.attr('id', id)
}
// Checks whether the given point inside the bounding box of the element
, inside: function(x, y) {
var box = this.bbox()
return x > box.x
&& y > box.y
&& x < box.x + box.width
&& y < box.y + box.height
}
// Show element
, show: function() {
return this.style('display', '')
}
// Hide element
, hide: function() {
return this.style('display', 'none')
}
// Is element visible?
, visible: function() {
return this.style('display') != 'none'
}
// Return id on string conversion
, toString: function() {
return this.attr('id')
}
// Return array of classes on the node
, classes: function() {
var attr = this.attr('class')
return attr == null ? [] : attr.trim().split(SVG.regex.delimiter)
}
// Return true if class exists on the node, false otherwise
, hasClass: function(name) {
return this.classes().indexOf(name) != -1
}
// Add class to the node
, addClass: function(name) {
if (!this.hasClass(name)) {
var array = this.classes()
array.push(name)
this.attr('class', array.join(' '))
}
return this
}
// Remove class from the node
, removeClass: function(name) {
if (this.hasClass(name)) {
this.attr('class', this.classes().filter(function(c) {
return c != name
}).join(' '))
}
return this
}
// Toggle the presence of a class on the node
, toggleClass: function(name) {
return this.hasClass(name) ? this.removeClass(name) : this.addClass(name)
}
// Get referenced element form attribute value
, reference: function(attr) {
return SVG.get(this.attr(attr))
}
// Returns the parent element instance
, parent: function(type) {
var parent = this
// check for parent
if(!parent.node.parentNode) return null
// get parent element
parent = SVG.adopt(parent.node.parentNode)
if(!type) return parent
// loop trough ancestors if type is given
while(parent && parent.node instanceof window.SVGElement){
if(typeof type === 'string' ? parent.matches(type) : parent instanceof type) return parent
parent = SVG.adopt(parent.node.parentNode)
}
}
// Get parent document
, doc: function() {
return this instanceof SVG.Doc ? this : this.parent(SVG.Doc)
}
// return array of all ancestors of given type up to the root svg
, parents: function(type) {
var parents = [], parent = this
do{
parent = parent.parent(type)
if(!parent || !parent.node) break
parents.push(parent)
} while(parent.parent)
return parents
}
// matches the element vs a css selector
, matches: function(selector){
return matches(this.node, selector)
}
// Returns the svg node to call native svg methods on it
, native: function() {
return this.node
}
// Import raw svg
, svg: function(svg) {
// create temporary holder
var well = document.createElement('svg')
// act as a setter if svg is given
if (svg && this instanceof SVG.Parent) {
// dump raw svg
well.innerHTML = '<svg>' + svg.replace(/\n/, '').replace(/<(\w+)([^<]+?)\/>/g, '<$1$2></$1>') + '</svg>'
// transplant nodes
for (var i = 0, il = well.firstChild.childNodes.length; i < il; i++)
this.node.appendChild(well.firstChild.firstChild)
// otherwise act as a getter
} else {
// create a wrapping svg element in case of partial content
well.appendChild(svg = document.createElement('svg'))
// write svgjs data to the dom
this.writeDataToDom()
// insert a copy of this node
svg.appendChild(this.node.cloneNode(true))
// return target element
return well.innerHTML.replace(/^<svg>/, '').replace(/<\/svg>$/, '')
}
return this
}
// write svgjs data to the dom
, writeDataToDom: function() {
// dump variables recursively
if(this.each || this.lines){
var fn = this.each ? this : this.lines();
fn.each(function(){
this.writeDataToDom()
})
}
// remove previously set data
this.node.removeAttribute('svgjs:data')
if(Object.keys(this.dom).length)
this.node.setAttribute('svgjs:data', JSON.stringify(this.dom)) // see #428
return this
}
// set given data to the elements data property
, setData: function(o){
this.dom = o
return this
}
, is: function(obj){
return is(this, obj)
}
}
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 | 2 | SVG.Circle = SVG.invent({
// Initialize node
create: 'circle'
// Inherit from
, inherit: SVG.Shape
// Add parent method
, construct: {
// Create circle element, based on ellipse
circle: function(size) {
return this.put(new SVG.Circle).rx(new SVG.Number(size).divide(2)).move(0, 0)
}
}
})
SVG.extend(SVG.Circle, SVG.FX, {
// Radius x value
rx: function(rx) {
return this.attr('r', rx)
}
// Alias radius x value
, ry: function(ry) {
return this.rx(ry)
}
})
SVG.Ellipse = SVG.invent({
// Initialize node
create: 'ellipse'
// Inherit from
, inherit: SVG.Shape
// Add parent method
, construct: {
// Create an ellipse
ellipse: function(width, height) {
return this.put(new SVG.Ellipse).size(width, height).move(0, 0)
}
}
})
SVG.extend(SVG.Ellipse, SVG.Rect, SVG.FX, {
// Radius x value
rx: function(rx) {
return this.attr('rx', rx)
}
// Radius y value
, ry: function(ry) {
return this.attr('ry', ry)
}
})
// Add common method
SVG.extend(SVG.Circle, SVG.Ellipse, {
// Move over x-axis
x: function(x) {
return x == null ? this.cx() - this.rx() : this.cx(x + this.rx())
}
// Move over y-axis
, y: function(y) {
return y == null ? this.cy() - this.ry() : this.cy(y + this.ry())
}
// Move by center over x-axis
, cx: function(x) {
return x == null ? this.attr('cx') : this.attr('cx', x)
}
// Move by center over y-axis
, cy: function(y) {
return y == null ? this.attr('cy') : this.attr('cy', y)
}
// Set width of element
, width: function(width) {
return width == null ? this.rx() * 2 : this.rx(new SVG.Number(width).divide(2))
}
// Set height of element
, height: function(height) {
return height == null ? this.ry() * 2 : this.ry(new SVG.Number(height).divide(2))
}
// Custom size function
, size: function(width, height) {
var p = proportionalSize(this, width, height)
return this
.rx(new SVG.Number(p.width).divide(2))
.ry(new SVG.Number(p.height).divide(2))
}
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 | 2 2 | // Add events to elements
;[ 'click'
, 'dblclick'
, 'mousedown'
, 'mouseup'
, 'mouseover'
, 'mouseout'
, 'mousemove'
// , 'mouseenter' -> not supported by IE
// , 'mouseleave' -> not supported by IE
, 'touchstart'
, 'touchmove'
, 'touchleave'
, 'touchend'
, 'touchcancel' ].forEach(function(event) {
// add event to SVG.Element
SVG.Element.prototype[event] = function(f) {
// bind event to element rather than element node
SVG.on(this.node, event, f)
return this
}
})
// Initialize listeners stack
SVG.listeners = []
SVG.handlerMap = []
SVG.listenerId = 0
// Add event binder in the SVG namespace
SVG.on = function(node, event, listener, binding, options) {
// create listener, get object-index
var l = listener.bind(binding || node.instance || node)
, index = (SVG.handlerMap.indexOf(node) + 1 || SVG.handlerMap.push(node)) - 1
, ev = event.split('.')[0]
, ns = event.split('.')[1] || '*'
// ensure valid object
SVG.listeners[index] = SVG.listeners[index] || {}
SVG.listeners[index][ev] = SVG.listeners[index][ev] || {}
SVG.listeners[index][ev][ns] = SVG.listeners[index][ev][ns] || {}
if(!listener._svgjsListenerId)
listener._svgjsListenerId = ++SVG.listenerId
// reference listener
SVG.listeners[index][ev][ns][listener._svgjsListenerId] = l
// add listener
node.addEventListener(ev, l, options || false)
}
// Add event unbinder in the SVG namespace
SVG.off = function(node, event, listener) {
var index = SVG.handlerMap.indexOf(node)
, ev = event && event.split('.')[0]
, ns = event && event.split('.')[1]
, namespace = ''
if(index == -1) return
if (listener) {
if(typeof listener == 'function') listener = listener._svgjsListenerId
if(!listener) return
// remove listener reference
if (SVG.listeners[index][ev] && SVG.listeners[index][ev][ns || '*']) {
// remove listener
node.removeEventListener(ev, SVG.listeners[index][ev][ns || '*'][listener], false)
delete SVG.listeners[index][ev][ns || '*'][listener]
}
} else if (ns && ev) {
// remove all listeners for a namespaced event
if (SVG.listeners[index][ev] && SVG.listeners[index][ev][ns]) {
for (listener in SVG.listeners[index][ev][ns])
SVG.off(node, [ev, ns].join('.'), listener)
delete SVG.listeners[index][ev][ns]
}
} else if (ns){
// remove all listeners for a specific namespace
for(event in SVG.listeners[index]){
for(namespace in SVG.listeners[index][event]){
if(ns === namespace){
SVG.off(node, [event, ns].join('.'))
}
}
}
} else if (ev) {
// remove all listeners for the event
if (SVG.listeners[index][ev]) {
for (namespace in SVG.listeners[index][ev])
SVG.off(node, [ev, namespace].join('.'))
delete SVG.listeners[index][ev]
}
} else {
// remove all listeners on a given node
for (event in SVG.listeners[index])
SVG.off(node, event)
delete SVG.listeners[index]
delete SVG.handlerMap[index]
}
}
//
SVG.extend(SVG.Element, {
// Bind given event to listener
on: function(event, listener, binding, options) {
SVG.on(this.node, event, listener, binding, options)
return this
}
// Unbind event from listener
, off: function(event, listener) {
SVG.off(this.node, event, listener)
return this
}
// Fire given event
, fire: function(event, data) {
// Dispatch event
if(event instanceof window.Event){
this.node.dispatchEvent(event)
}else{
this.node.dispatchEvent(event = new window.CustomEvent(event, {detail:data, cancelable: true}))
}
this._event = event
return this
}
, event: function() {
return this._event
}
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 | 2 | SVG.easing = {
'-': function(pos){return pos}
, '<>':function(pos){return -Math.cos(pos * Math.PI) / 2 + 0.5}
, '>': function(pos){return Math.sin(pos * Math.PI / 2)}
, '<': function(pos){return -Math.cos(pos * Math.PI / 2) + 1}
}
SVG.morph = function(pos){
return function(from, to) {
return new SVG.MorphObj(from, to).at(pos)
}
}
SVG.Situation = SVG.invent({
create: function(o){
this.init = false
this.reversed = false
this.reversing = false
this.duration = new SVG.Number(o.duration).valueOf()
this.delay = new SVG.Number(o.delay).valueOf()
this.start = +new Date() + this.delay
this.finish = this.start + this.duration
this.ease = o.ease
// this.loop is incremented from 0 to this.loops
// it is also incremented when in an infinite loop (when this.loops is true)
this.loop = 0
this.loops = false
this.animations = {
// functionToCall: [list of morphable objects]
// e.g. move: [SVG.Number, SVG.Number]
}
this.attrs = {
// holds all attributes which are not represented from a function svg.js provides
// e.g. someAttr: SVG.Number
}
this.styles = {
// holds all styles which should be animated
// e.g. fill-color: SVG.Color
}
this.transforms = [
// holds all transformations as transformation objects
// e.g. [SVG.Rotate, SVG.Translate, SVG.Matrix]
]
this.once = {
// functions to fire at a specific position
// e.g. "0.5": function foo(){}
}
}
})
SVG.FX = SVG.invent({
create: function(element) {
this._target = element
this.situations = []
this.active = false
this.situation = null
this.paused = false
this.lastPos = 0
this.pos = 0
// The absolute position of an animation is its position in the context of its complete duration (including delay and loops)
// When performing a delay, absPos is below 0 and when performing a loop, its value is above 1
this.absPos = 0
this._speed = 1
}
, extend: {
/**
* sets or returns the target of this animation
* @param o object || number In case of Object it holds all parameters. In case of number its the duration of the animation
* @param ease function || string Function which should be used for easing or easing keyword
* @param delay Number indicating the delay before the animation starts
* @return target || this
*/
animate: function(o, ease, delay){
if(typeof o == 'object'){
ease = o.ease
delay = o.delay
o = o.duration
}
var situation = new SVG.Situation({
duration: o || 1000,
delay: delay || 0,
ease: SVG.easing[ease || '-'] || ease
})
this.queue(situation)
return this
}
/**
* sets a delay before the next element of the queue is called
* @param delay Duration of delay in milliseconds
* @return this.target()
*/
, delay: function(delay){
// The delay is performed by an empty situation with its duration
// attribute set to the duration of the delay
var situation = new SVG.Situation({
duration: delay,
delay: 0,
ease: SVG.easing['-']
})
return this.queue(situation)
}
/**
* sets or returns the target of this animation
* @param null || target SVG.Element which should be set as new target
* @return target || this
*/
, target: function(target){
if(target && target instanceof SVG.Element){
this._target = target
return this
}
return this._target
}
// returns the absolute position at a given time
, timeToAbsPos: function(timestamp){
return (timestamp - this.situation.start) / (this.situation.duration/this._speed)
}
// returns the timestamp from a given absolute positon
, absPosToTime: function(absPos){
return this.situation.duration/this._speed * absPos + this.situation.start
}
// starts the animationloop
, startAnimFrame: function(){
this.stopAnimFrame()
this.animationFrame = window.requestAnimationFrame(function(){ this.step() }.bind(this))
}
// cancels the animationframe
, stopAnimFrame: function(){
window.cancelAnimationFrame(this.animationFrame)
}
// kicks off the animation - only does something when the queue is currently not active and at least one situation is set
, start: function(){
// dont start if already started
if(!this.active && this.situation){
this.active = true
this.startCurrent()
}
return this
}
// start the current situation
, startCurrent: function(){
this.situation.start = +new Date + this.situation.delay/this._speed
this.situation.finish = this.situation.start + this.situation.duration/this._speed
return this.initAnimations().step()
}
/**
* adds a function / Situation to the animation queue
* @param fn function / situation to add
* @return this
*/
, queue: function(fn){
if(typeof fn == 'function' || fn instanceof SVG.Situation)
this.situations.push(fn)
if(!this.situation) this.situation = this.situations.shift()
return this
}
/**
* pulls next element from the queue and execute it
* @return this
*/
, dequeue: function(){
// stop current animation
this.stop()
// get next animation from queue
this.situation = this.situations.shift()
if(this.situation){
if(this.situation instanceof SVG.Situation) {
this.start()
} else {
// If it is not a SVG.Situation, then it is a function, we execute it
this.situation.call(this)
}
}
return this
}
// updates all animations to the current state of the element
// this is important when one property could be changed from another property
, initAnimations: function() {
var i, source
var s = this.situation
if(s.init) return this
for(i in s.animations){
source = this.target()[i]()
// The condition is because some methods return a normal number instead
// of a SVG.Number
if(s.animations[i] instanceof SVG.Number)
source = new SVG.Number(source)
s.animations[i] = source.morph(s.animations[i])
}
for(i in s.attrs){
s.attrs[i] = new SVG.MorphObj(this.target().attr(i), s.attrs[i])
}
for(i in s.styles){
s.styles[i] = new SVG.MorphObj(this.target().style(i), s.styles[i])
}
s.initialTransformation = this.target().matrixify()
s.init = true
return this
}
, clearQueue: function(){
this.situations = []
return this
}
, clearCurrent: function(){
this.situation = null
return this
}
/** stops the animation immediately
* @param jumpToEnd A Boolean indicating whether to complete the current animation immediately.
* @param clearQueue A Boolean indicating whether to remove queued animation as well.
* @return this
*/
, stop: function(jumpToEnd, clearQueue){
var active = this.active
this.active = false
if(clearQueue){
this.clearQueue()
}
if(jumpToEnd && this.situation){
// initialize the situation if it was not
!active && this.startCurrent()
this.atEnd()
}
this.stopAnimFrame()
return this.clearCurrent()
}
/** resets the element to the state where the current element has started
* @return this
*/
, reset: function(){
if(this.situation){
var temp = this.situation
this.stop()
this.situation = temp
this.atStart()
}
return this
}
// Stop the currently-running animation, remove all queued animations, and complete all animations for the element.
, finish: function(){
this.stop(true, false)
while(this.dequeue().situation && this.stop(true, false));
this.clearQueue().clearCurrent()
return this
}
// set the internal animation pointer at the start position, before any loops, and updates the visualisation
, atStart: function() {
return this.at(0, true)
}
// set the internal animation pointer at the end position, after all the loops, and updates the visualisation
, atEnd: function() {
if (this.situation.loops === true) {
// If in a infinite loop, we end the current iteration
this.situation.loops = this.situation.loop + 1
}
if(typeof this.situation.loops == 'number') {
// If performing a finite number of loops, we go after all the loops
return this.at(this.situation.loops, true)
} else {
// If no loops, we just go at the end
return this.at(1, true)
}
}
// set the internal animation pointer to the specified position and updates the visualisation
// if isAbsPos is true, pos is treated as an absolute position
, at: function(pos, isAbsPos){
var durDivSpd = this.situation.duration/this._speed
this.absPos = pos
// If pos is not an absolute position, we convert it into one
if (!isAbsPos) {
if (this.situation.reversed) this.absPos = 1 - this.absPos
this.absPos += this.situation.loop
}
this.situation.start = +new Date - this.absPos * durDivSpd
this.situation.finish = this.situation.start + durDivSpd
return this.step(true)
}
/**
* sets or returns the speed of the animations
* @param speed null || Number The new speed of the animations
* @return Number || this
*/
, speed: function(speed){
if (speed === 0) return this.pause()
if (speed) {
this._speed = speed
// We use an absolute position here so that speed can affect the delay before the animation
return this.at(this.absPos, true)
} else return this._speed
}
// Make loopable
, loop: function(times, reverse) {
var c = this.last()
// store total loops
c.loops = (times != null) ? times : true
c.loop = 0
if(reverse) c.reversing = true
return this
}
// pauses the animation
, pause: function(){
this.paused = true
this.stopAnimFrame()
return this
}
// unpause the animation
, play: function(){
if(!this.paused) return this
this.paused = false
// We use an absolute position here so that the delay before the animation can be paused
return this.at(this.absPos, true)
}
/**
* toggle or set the direction of the animation
* true sets direction to backwards while false sets it to forwards
* @param reversed Boolean indicating whether to reverse the animation or not (default: toggle the reverse status)
* @return this
*/
, reverse: function(reversed){
var c = this.last()
if(typeof reversed == 'undefined') c.reversed = !c.reversed
else c.reversed = reversed
return this
}
/**
* returns a float from 0-1 indicating the progress of the current animation
* @param eased Boolean indicating whether the returned position should be eased or not
* @return number
*/
, progress: function(easeIt){
return easeIt ? this.situation.ease(this.pos) : this.pos
}
/**
* adds a callback function which is called when the current animation is finished
* @param fn Function which should be executed as callback
* @return number
*/
, after: function(fn){
var c = this.last()
, wrapper = function wrapper(e){
if(e.detail.situation == c){
fn.call(this, c)
this.off('finished.fx', wrapper) // prevent memory leak
}
}
this.target().on('finished.fx', wrapper)
return this._callStart()
}
// adds a callback which is called whenever one animation step is performed
, during: function(fn){
var c = this.last()
, wrapper = function(e){
if(e.detail.situation == c){
fn.call(this, e.detail.pos, SVG.morph(e.detail.pos), e.detail.eased, c)
}
}
// see above
this.target().off('during.fx', wrapper).on('during.fx', wrapper)
this.after(function(){
this.off('during.fx', wrapper)
})
return this._callStart()
}
// calls after ALL animations in the queue are finished
, afterAll: function(fn){
var wrapper = function wrapper(e){
fn.call(this)
this.off('allfinished.fx', wrapper)
}
// see above
this.target().off('allfinished.fx', wrapper).on('allfinished.fx', wrapper)
return this._callStart()
}
// calls on every animation step for all animations
, duringAll: function(fn){
var wrapper = function(e){
fn.call(this, e.detail.pos, SVG.morph(e.detail.pos), e.detail.eased, e.detail.situation)
}
this.target().off('during.fx', wrapper).on('during.fx', wrapper)
this.afterAll(function(){
this.off('during.fx', wrapper)
})
return this._callStart()
}
, last: function(){
return this.situations.length ? this.situations[this.situations.length-1] : this.situation
}
// adds one property to the animations
, add: function(method, args, type){
this.last()[type || 'animations'][method] = args
return this._callStart()
}
/** perform one step of the animation
* @param ignoreTime Boolean indicating whether to ignore time and use position directly or recalculate position based on time
* @return this
*/
, step: function(ignoreTime){
// convert current time to an absolute position
if(!ignoreTime) this.absPos = this.timeToAbsPos(+new Date)
// This part convert an absolute position to a position
if(this.situation.loops !== false) {
var absPos, absPosInt, lastLoop
// If the absolute position is below 0, we just treat it as if it was 0
absPos = Math.max(this.absPos, 0)
absPosInt = Math.floor(absPos)
if(this.situation.loops === true || absPosInt < this.situation.loops) {
this.pos = absPos - absPosInt
lastLoop = this.situation.loop
this.situation.loop = absPosInt
} else {
this.absPos = this.situation.loops
this.pos = 1
// The -1 here is because we don't want to toggle reversed when all the loops have been completed
lastLoop = this.situation.loop - 1
this.situation.loop = this.situation.loops
}
if(this.situation.reversing) {
// Toggle reversed if an odd number of loops as occured since the last call of step
this.situation.reversed = this.situation.reversed != Boolean((this.situation.loop - lastLoop) % 2)
}
} else {
// If there are no loop, the absolute position must not be above 1
this.absPos = Math.min(this.absPos, 1)
this.pos = this.absPos
}
// while the absolute position can be below 0, the position must not be below 0
if(this.pos < 0) this.pos = 0
if(this.situation.reversed) this.pos = 1 - this.pos
// apply easing
var eased = this.situation.ease(this.pos)
// call once-callbacks
for(var i in this.situation.once){
if(i > this.lastPos && i <= eased){
this.situation.once[i].call(this.target(), this.pos, eased)
delete this.situation.once[i]
}
}
// fire during callback with position, eased position and current situation as parameter
if(this.active) this.target().fire('during', {pos: this.pos, eased: eased, fx: this, situation: this.situation})
// the user may call stop or finish in the during callback
// so make sure that we still have a valid situation
if(!this.situation){
return this
}
// apply the actual animation to every property
this.eachAt()
// do final code when situation is finished
if((this.pos == 1 && !this.situation.reversed) || (this.situation.reversed && this.pos == 0)){
// stop animation callback
this.stopAnimFrame()
// fire finished callback with current situation as parameter
this.target().fire('finished', {fx:this, situation: this.situation})
if(!this.situations.length){
this.target().fire('allfinished')
this.target().off('.fx') // there shouldnt be any binding left, but to make sure...
this.active = false
}
// start next animation
if(this.active) this.dequeue()
else this.clearCurrent()
}else if(!this.paused && this.active){
// we continue animating when we are not at the end
this.startAnimFrame()
}
// save last eased position for once callback triggering
this.lastPos = eased
return this
}
// calculates the step for every property and calls block with it
, eachAt: function(){
var i, len, at, self = this, target = this.target(), s = this.situation
// apply animations which can be called trough a method
for(i in s.animations){
at = [].concat(s.animations[i]).map(function(el){
return typeof el !== 'string' && el.at ? el.at(s.ease(self.pos), self.pos) : el
})
target[i].apply(target, at)
}
// apply animation which has to be applied with attr()
for(i in s.attrs){
at = [i].concat(s.attrs[i]).map(function(el){
return typeof el !== 'string' && el.at ? el.at(s.ease(self.pos), self.pos) : el
})
target.attr.apply(target, at)
}
// apply animation which has to be applied with style()
for(i in s.styles){
at = [i].concat(s.styles[i]).map(function(el){
return typeof el !== 'string' && el.at ? el.at(s.ease(self.pos), self.pos) : el
})
target.style.apply(target, at)
}
// animate initialTransformation which has to be chained
if(s.transforms.length){
// get initial initialTransformation
at = s.initialTransformation
for(i = 0, len = s.transforms.length; i < len; i++){
// get next transformation in chain
var a = s.transforms[i]
// multiply matrix directly
if(a instanceof SVG.Matrix){
if(a.relative){
at = at.multiply(new SVG.Matrix().morph(a).at(s.ease(this.pos)))
}else{
at = at.morph(a).at(s.ease(this.pos))
}
continue
}
// when transformation is absolute we have to reset the needed transformation first
if(!a.relative)
a.undo(at.extract())
// and reapply it after
at = at.multiply(a.at(s.ease(this.pos)))
}
// set new matrix on element
target.matrix(at)
}
return this
}
// adds an once-callback which is called at a specific position and never again
, once: function(pos, fn, isEased){
if(!isEased)pos = this.situation.ease(pos)
this.situation.once[pos] = fn
return this
}
, _callStart: function() {
setTimeout(function(){this.start()}.bind(this), 0)
return this
}
}
, parent: SVG.Element
// Add method to parent elements
, construct: {
// Get fx module or create a new one, then animate with given duration and ease
animate: function(o, ease, delay) {
return (this.fx || (this.fx = new SVG.FX(this))).animate(o, ease, delay)
}
, delay: function(delay){
return (this.fx || (this.fx = new SVG.FX(this))).delay(delay)
}
, stop: function(jumpToEnd, clearQueue) {
if (this.fx)
this.fx.stop(jumpToEnd, clearQueue)
return this
}
, finish: function() {
if (this.fx)
this.fx.finish()
return this
}
// Pause current animation
, pause: function() {
if (this.fx)
this.fx.pause()
return this
}
// Play paused current animation
, play: function() {
if (this.fx)
this.fx.play()
return this
}
// Set/Get the speed of the animations
, speed: function(speed) {
if (this.fx)
if (speed == null)
return this.fx.speed()
else
this.fx.speed(speed)
return this
}
}
})
// MorphObj is used whenever no morphable object is given
SVG.MorphObj = SVG.invent({
create: function(from, to){
// prepare color for morphing
if(SVG.Color.isColor(to)) return new SVG.Color(from).morph(to)
// prepare number for morphing
if(SVG.regex.numberAndUnit.test(to)) return new SVG.Number(from).morph(to)
// prepare for plain morphing
this.value = from
this.destination = to
}
, extend: {
at: function(pos, real){
return real < 1 ? this.value : this.destination
},
valueOf: function(){
return this.value
}
}
})
SVG.extend(SVG.FX, {
// Add animatable attributes
attr: function(a, v, relative) {
// apply attributes individually
if (typeof a == 'object') {
for (var key in a)
this.attr(key, a[key])
} else {
this.add(a, v, 'attrs')
}
return this
}
// Add animatable styles
, style: function(s, v) {
if (typeof s == 'object')
for (var key in s)
this.style(key, s[key])
else
this.add(s, v, 'styles')
return this
}
// Animatable x-axis
, x: function(x, relative) {
if(this.target() instanceof SVG.G){
this.transform({x:x}, relative)
return this
}
var num = new SVG.Number(x)
num.relative = relative
return this.add('x', num)
}
// Animatable y-axis
, y: function(y, relative) {
if(this.target() instanceof SVG.G){
this.transform({y:y}, relative)
return this
}
var num = new SVG.Number(y)
num.relative = relative
return this.add('y', num)
}
// Animatable center x-axis
, cx: function(x) {
return this.add('cx', new SVG.Number(x))
}
// Animatable center y-axis
, cy: function(y) {
return this.add('cy', new SVG.Number(y))
}
// Add animatable move
, move: function(x, y) {
return this.x(x).y(y)
}
// Add animatable center
, center: function(x, y) {
return this.cx(x).cy(y)
}
// Add animatable size
, size: function(width, height) {
if (this.target() instanceof SVG.Text) {
// animate font size for Text elements
this.attr('font-size', width)
} else {
// animate bbox based size for all other elements
var box
if(!width || !height){
box = this.target().bbox()
}
if(!width){
width = box.width / box.height * height
}
if(!height){
height = box.height / box.width * width
}
this.add('width' , new SVG.Number(width))
.add('height', new SVG.Number(height))
}
return this
}
// Add animatable plot
, plot: function() {
// We use arguments here since SVG.Line's plot method can be passed 4 parameters
return this.add('plot', arguments.length > 1 ? [].slice.call(arguments) : arguments[0])
}
// Add leading method
, leading: function(value) {
return this.target().leading ?
this.add('leading', new SVG.Number(value)) :
this
}
// Add animatable viewbox
, viewbox: function(x, y, width, height) {
if (this.target() instanceof SVG.Container) {
this.add('viewbox', new SVG.ViewBox(x, y, width, height))
}
return this
}
, update: function(o) {
if (this.target() instanceof SVG.Stop) {
if (typeof o == 'number' || o instanceof SVG.Number) {
return this.update({
offset: arguments[0]
, color: arguments[1]
, opacity: arguments[2]
})
}
if (o.opacity != null) this.attr('stop-opacity', o.opacity)
if (o.color != null) this.attr('stop-color', o.color)
if (o.offset != null) this.attr('offset', o.offset)
}
return this
}
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 | 2 | SVG.Gradient = SVG.invent({
// Initialize node
create: function(type) {
this.constructor.call(this, SVG.create(type + 'Gradient'))
// store type
this.type = type
}
// Inherit from
, inherit: SVG.Container
// Add class methods
, extend: {
// Add a color stop
at: function(offset, color, opacity) {
return this.put(new SVG.Stop).update(offset, color, opacity)
}
// Update gradient
, update: function(block) {
// remove all stops
this.clear()
// invoke passed block
if (typeof block == 'function')
block.call(this, this)
return this
}
// Return the fill id
, fill: function() {
return 'url(#' + this.id() + ')'
}
// Alias string convertion to fill
, toString: function() {
return this.fill()
}
// custom attr to handle transform
, attr: function(a, b, c) {
if(a == 'transform') a = 'gradientTransform'
return SVG.Container.prototype.attr.call(this, a, b, c)
}
}
// Add parent method
, construct: {
// Create gradient element in defs
gradient: function(type, block) {
return this.defs().gradient(type, block)
}
}
})
// Add animatable methods to both gradient and fx module
SVG.extend(SVG.Gradient, SVG.FX, {
// From position
from: function(x, y) {
return (this._target || this).type == 'radial' ?
this.attr({ fx: new SVG.Number(x), fy: new SVG.Number(y) }) :
this.attr({ x1: new SVG.Number(x), y1: new SVG.Number(y) })
}
// To position
, to: function(x, y) {
return (this._target || this).type == 'radial' ?
this.attr({ cx: new SVG.Number(x), cy: new SVG.Number(y) }) :
this.attr({ x2: new SVG.Number(x), y2: new SVG.Number(y) })
}
})
// Base gradient generation
SVG.extend(SVG.Defs, {
// define gradient
gradient: function(type, block) {
return this.put(new SVG.Gradient(type)).update(block)
}
})
SVG.Stop = SVG.invent({
// Initialize node
create: 'stop'
// Inherit from
, inherit: SVG.Element
// Add class methods
, extend: {
// add color stops
update: function(o) {
if (typeof o == 'number' || o instanceof SVG.Number) {
o = {
offset: arguments[0]
, color: arguments[1]
, opacity: arguments[2]
}
}
// set attributes
if (o.opacity != null) this.attr('stop-opacity', o.opacity)
if (o.color != null) this.attr('stop-color', o.color)
if (o.offset != null) this.attr('offset', new SVG.Number(o.offset))
return this
}
}
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | 2 | SVG.G = SVG.invent({
// Initialize node
create: 'g'
// Inherit from
, inherit: SVG.Container
// Add class methods
, extend: {
// Move over x-axis
x: function(x) {
return x == null ? this.transform('x') : this.transform({ x: x - this.x() }, true)
}
// Move over y-axis
, y: function(y) {
return y == null ? this.transform('y') : this.transform({ y: y - this.y() }, true)
}
// Move by center over x-axis
, cx: function(x) {
return x == null ? this.gbox().cx : this.x(x - this.gbox().width / 2)
}
// Move by center over y-axis
, cy: function(y) {
return y == null ? this.gbox().cy : this.y(y - this.gbox().height / 2)
}
, gbox: function() {
var bbox = this.bbox()
, trans = this.transform()
bbox.x += trans.x
bbox.x2 += trans.x
bbox.cx += trans.x
bbox.y += trans.y
bbox.y2 += trans.y
bbox.cy += trans.y
return bbox
}
}
// Add parent method
, construct: {
// Create a group element
group: function() {
return this.put(new SVG.G)
}
}
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 | 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 | function pathRegReplace(a, b, c, d) { return c + d.replace(SVG.regex.dots, ' .') } // creates deep clone of array function array_clone(arr){ var clone = arr.slice(0) for(var i = clone.length; i--;){ if(Array.isArray(clone[i])){ clone[i] = array_clone(clone[i]) } } return clone } // tests if a given element is instance of an object function is(el, obj){ return el instanceof obj } // tests if a given selector matches an element function matches(el, selector) { return (el.matches || el.matchesSelector || el.msMatchesSelector || el.mozMatchesSelector || el.webkitMatchesSelector || el.oMatchesSelector).call(el, selector); } // Convert dash-separated-string to camelCase function camelCase(s) { return s.toLowerCase().replace(/-(.)/g, function(m, g) { return g.toUpperCase() }) } // Capitalize first letter of a string function capitalize(s) { return s.charAt(0).toUpperCase() + s.slice(1) } // Ensure to six-based hex function fullHex(hex) { return hex.length == 4 ? [ '#', hex.substring(1, 2), hex.substring(1, 2) , hex.substring(2, 3), hex.substring(2, 3) , hex.substring(3, 4), hex.substring(3, 4) ].join('') : hex } // Component to hex value function compToHex(comp) { var hex = comp.toString(16) return hex.length == 1 ? '0' + hex : hex } // Calculate proportional width and height values when necessary function proportionalSize(element, width, height) { if (width == null || height == null) { var box = element.bbox() if (width == null) width = box.width / box.height * height else if (height == null) height = box.height / box.width * width } return { width: width , height: height } } // Delta transform point function deltaTransformPoint(matrix, x, y) { return { x: x * matrix.a + y * matrix.c + 0 , y: x * matrix.b + y * matrix.d + 0 } } // Map matrix array to object function arrayToMatrix(a) { return { a: a[0], b: a[1], c: a[2], d: a[3], e: a[4], f: a[5] } } // Parse matrix if required function parseMatrix(matrix) { if (!(matrix instanceof SVG.Matrix)) matrix = new SVG.Matrix(matrix) return matrix } // Add centre point to transform object function ensureCentre(o, target) { o.cx = o.cx == null ? target.bbox().cx : o.cx o.cy = o.cy == null ? target.bbox().cy : o.cy } // PathArray Helpers function arrayToString(a) { for (var i = 0, il = a.length, s = ''; i < il; i++) { s += a[i][0] if (a[i][1] != null) { s += a[i][1] if (a[i][2] != null) { s += ' ' s += a[i][2] if (a[i][3] != null) { s += ' ' s += a[i][3] s += ' ' s += a[i][4] if (a[i][5] != null) { s += ' ' s += a[i][5] s += ' ' s += a[i][6] if (a[i][7] != null) { s += ' ' s += a[i][7] } } } } } } return s + ' ' } // Deep new id assignment function assignNewId(node) { // do the same for SVG child nodes as well for (var i = node.childNodes.length - 1; i >= 0; i--) if (node.childNodes[i] instanceof window.SVGElement) assignNewId(node.childNodes[i]) return SVG.adopt(node).id(SVG.eid(node.nodeName)) } // Add more bounding box properties function fullBox(b) { if (b.x == null) { b.x = 0 b.y = 0 b.width = 0 b.height = 0 } b.w = b.width b.h = b.height b.x2 = b.x + b.width b.y2 = b.y + b.height b.cx = b.x + b.width / 2 b.cy = b.y + b.height / 2 return b } // Get id from reference string function idFromReference(url) { var m = url.toString().match(SVG.regex.reference) if (m) return m[1] } // Create matrix array for looping var abcdef = 'abcdef'.split('') |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | 2 | SVG.A = SVG.invent({
// Initialize node
create: 'a'
// Inherit from
, inherit: SVG.Container
// Add class methods
, extend: {
// Link url
to: function(url) {
return this.attr('href', url, SVG.xlink)
}
// Link show attribute
, show: function(target) {
return this.attr('show', target, SVG.xlink)
}
// Link target attribute
, target: function(target) {
return this.attr('target', target)
}
}
// Add parent method
, construct: {
// Create a hyperlink element
link: function(url) {
return this.put(new SVG.A).to(url)
}
}
})
SVG.extend(SVG.Element, {
// Create a hyperlink element
linkTo: function(url) {
var link = new SVG.A
if (typeof url == 'function')
url.call(link, link)
else
link.to(url)
return this.parent().put(link).put(this)
}
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | 2 | SVG.Image = SVG.invent({
// Initialize node
create: 'image'
// Inherit from
, inherit: SVG.Shape
// Add class methods
, extend: {
// (re)load image
load: function(url) {
if (!url) return this
var self = this
, img = new window.Image()
// preload image
SVG.on(img, 'load', function() {
var p = self.parent(SVG.Pattern)
if(p === null) return
// ensure image size
if (self.width() == 0 && self.height() == 0)
self.size(img.width, img.height)
// ensure pattern size if not set
if (p && p.width() == 0 && p.height() == 0)
p.size(self.width(), self.height())
// callback
if (typeof self._loaded === 'function')
self._loaded.call(self, {
width: img.width
, height: img.height
, ratio: img.width / img.height
, url: url
})
})
SVG.on(img, 'error', function(e){
if (typeof self._error === 'function'){
self._error.call(self, e)
}
})
return this.attr('href', (img.src = this.src = url), SVG.xlink)
}
// Add loaded callback
, loaded: function(loaded) {
this._loaded = loaded
return this
}
, error: function(error) {
this._error = error
return this
}
}
// Add parent method
, construct: {
// create image element, load image and set its size
image: function(source, width, height) {
return this.put(new SVG.Image).load(source).size(width || 0, height || width || 0)
}
}
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | 2 | SVG.Line = SVG.invent({
// Initialize node
create: 'line'
// Inherit from
, inherit: SVG.Shape
// Add class methods
, extend: {
// Get array
array: function() {
return new SVG.PointArray([
[ this.attr('x1'), this.attr('y1') ]
, [ this.attr('x2'), this.attr('y2') ]
])
}
// Overwrite native plot() method
, plot: function(x1, y1, x2, y2) {
if (x1 == null)
return this.array()
else if (typeof y1 !== 'undefined')
x1 = { x1: x1, y1: y1, x2: x2, y2: y2 }
else
x1 = new SVG.PointArray(x1).toLine()
return this.attr(x1)
}
// Move by left top corner
, move: function(x, y) {
return this.attr(this.array().move(x, y).toLine())
}
// Set element size to given width and height
, size: function(width, height) {
var p = proportionalSize(this, width, height)
return this.attr(this.array().size(p.width, p.height).toLine())
}
}
// Add parent method
, construct: {
// Create a line element
line: function(x1, y1, x2, y2) {
// make sure plot is called as a setter
// x1 is not necessarily a number, it can also be an array, a string and a SVG.PointArray
return SVG.Line.prototype.plot.apply(
this.put(new SVG.Line)
, x1 != null ? [x1, y1, x2, y2] : [0, 0, 0, 0]
)
}
}
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | 2 | SVG.Marker = SVG.invent({
// Initialize node
create: 'marker'
// Inherit from
, inherit: SVG.Container
// Add class methods
, extend: {
// Set width of element
width: function(width) {
return this.attr('markerWidth', width)
}
// Set height of element
, height: function(height) {
return this.attr('markerHeight', height)
}
// Set marker refX and refY
, ref: function(x, y) {
return this.attr('refX', x).attr('refY', y)
}
// Update marker
, update: function(block) {
// remove all content
this.clear()
// invoke passed block
if (typeof block == 'function')
block.call(this, this)
return this
}
// Return the fill id
, toString: function() {
return 'url(#' + this.id() + ')'
}
}
// Add parent method
, construct: {
marker: function(width, height, block) {
// Create marker element in defs
return this.defs().marker(width, height, block)
}
}
})
SVG.extend(SVG.Defs, {
// Create marker
marker: function(width, height, block) {
// Set default viewbox to match the width and height, set ref to cx and cy and set orient to auto
return this.put(new SVG.Marker)
.size(width, height)
.ref(width / 2, height / 2)
.viewbox(0, 0, width, height)
.attr('orient', 'auto')
.update(block)
}
})
SVG.extend(SVG.Line, SVG.Polyline, SVG.Polygon, SVG.Path, {
// Create and attach markers
marker: function(marker, width, height, block) {
var attr = ['marker']
// Build attribute name
if (marker != 'all') attr.push(marker)
attr = attr.join('-')
// Set marker attribute
marker = arguments[1] instanceof SVG.Marker ?
arguments[1] :
this.doc().marker(width, height, block)
return this.attr(attr, marker)
}
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | 2 | SVG.Mask = SVG.invent({
// Initialize node
create: function() {
this.constructor.call(this, SVG.create('mask'))
// keep references to masked elements
this.targets = []
}
// Inherit from
, inherit: SVG.Container
// Add class methods
, extend: {
// Unmask all masked elements and remove itself
remove: function() {
// unmask all targets
for (var i = this.targets.length - 1; i >= 0; i--)
if (this.targets[i])
this.targets[i].unmask()
this.targets = []
// remove mask from parent
this.parent().removeElement(this)
return this
}
}
// Add parent method
, construct: {
// Create masking element
mask: function() {
return this.defs().put(new SVG.Mask)
}
}
})
SVG.extend(SVG.Element, {
// Distribute mask to svg element
maskWith: function(element) {
// use given mask or create a new one
this.masker = element instanceof SVG.Mask ? element : this.parent().mask().add(element)
// store reverence on self in mask
this.masker.targets.push(this)
// apply mask
return this.attr('mask', 'url("#' + this.masker.attr('id') + '")')
}
// Unmask element
, unmask: function() {
delete this.masker
return this.attr('mask', null)
}
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 | 2 | SVG.Matrix = SVG.invent({
// Initialize
create: function(source) {
var i, base = arrayToMatrix([1, 0, 0, 1, 0, 0])
// ensure source as object
source = source instanceof SVG.Element ?
source.matrixify() :
typeof source === 'string' ?
arrayToMatrix(source.split(SVG.regex.delimiter).map(parseFloat)) :
arguments.length == 6 ?
arrayToMatrix([].slice.call(arguments)) :
Array.isArray(source) ?
arrayToMatrix(source) :
typeof source === 'object' ?
source : base
// merge source
for (i = abcdef.length - 1; i >= 0; --i)
this[abcdef[i]] = source && typeof source[abcdef[i]] === 'number' ?
source[abcdef[i]] : base[abcdef[i]]
}
// Add methods
, extend: {
// Extract individual transformations
extract: function() {
// find delta transform points
var px = deltaTransformPoint(this, 0, 1)
, py = deltaTransformPoint(this, 1, 0)
, skewX = 180 / Math.PI * Math.atan2(px.y, px.x) - 90
return {
// translation
x: this.e
, y: this.f
, transformedX:(this.e * Math.cos(skewX * Math.PI / 180) + this.f * Math.sin(skewX * Math.PI / 180)) / Math.sqrt(this.a * this.a + this.b * this.b)
, transformedY:(this.f * Math.cos(skewX * Math.PI / 180) + this.e * Math.sin(-skewX * Math.PI / 180)) / Math.sqrt(this.c * this.c + this.d * this.d)
// skew
, skewX: -skewX
, skewY: 180 / Math.PI * Math.atan2(py.y, py.x)
// scale
, scaleX: Math.sqrt(this.a * this.a + this.b * this.b)
, scaleY: Math.sqrt(this.c * this.c + this.d * this.d)
// rotation
, rotation: skewX
, a: this.a
, b: this.b
, c: this.c
, d: this.d
, e: this.e
, f: this.f
, matrix: new SVG.Matrix(this)
}
}
// Clone matrix
, clone: function() {
return new SVG.Matrix(this)
}
// Morph one matrix into another
, morph: function(matrix) {
// store new destination
this.destination = new SVG.Matrix(matrix)
return this
}
// Get morphed matrix at a given position
, at: function(pos) {
// make sure a destination is defined
if (!this.destination) return this
// calculate morphed matrix at a given position
var matrix = new SVG.Matrix({
a: this.a + (this.destination.a - this.a) * pos
, b: this.b + (this.destination.b - this.b) * pos
, c: this.c + (this.destination.c - this.c) * pos
, d: this.d + (this.destination.d - this.d) * pos
, e: this.e + (this.destination.e - this.e) * pos
, f: this.f + (this.destination.f - this.f) * pos
})
return matrix
}
// Multiplies by given matrix
, multiply: function(matrix) {
return new SVG.Matrix(this.native().multiply(parseMatrix(matrix).native()))
}
// Inverses matrix
, inverse: function() {
return new SVG.Matrix(this.native().inverse())
}
// Translate matrix
, translate: function(x, y) {
return new SVG.Matrix(this.native().translate(x || 0, y || 0))
}
// Scale matrix
, scale: function(x, y, cx, cy) {
// support uniformal scale
if (arguments.length == 1) {
y = x
} else if (arguments.length == 3) {
cy = cx
cx = y
y = x
}
return this.around(cx, cy, new SVG.Matrix(x, 0, 0, y, 0, 0))
}
// Rotate matrix
, rotate: function(r, cx, cy) {
// convert degrees to radians
r = SVG.utils.radians(r)
return this.around(cx, cy, new SVG.Matrix(Math.cos(r), Math.sin(r), -Math.sin(r), Math.cos(r), 0, 0))
}
// Flip matrix on x or y, at a given offset
, flip: function(a, o) {
return a == 'x' ?
this.scale(-1, 1, o, 0) :
a == 'y' ?
this.scale(1, -1, 0, o) :
this.scale(-1, -1, a, o != null ? o : a)
}
// Skew
, skew: function(x, y, cx, cy) {
// support uniformal skew
if (arguments.length == 1) {
y = x
} else if (arguments.length == 3) {
cy = cx
cx = y
y = x
}
// convert degrees to radians
x = SVG.utils.radians(x)
y = SVG.utils.radians(y)
return this.around(cx, cy, new SVG.Matrix(1, Math.tan(y), Math.tan(x), 1, 0, 0))
}
// SkewX
, skewX: function(x, cx, cy) {
return this.skew(x, 0, cx, cy)
}
// SkewY
, skewY: function(y, cx, cy) {
return this.skew(0, y, cx, cy)
}
// Transform around a center point
, around: function(cx, cy, matrix) {
return this
.multiply(new SVG.Matrix(1, 0, 0, 1, cx || 0, cy || 0))
.multiply(matrix)
.multiply(new SVG.Matrix(1, 0, 0, 1, -cx || 0, -cy || 0))
}
// Convert to native SVGMatrix
, native: function() {
// create new matrix
var matrix = SVG.parser.native.createSVGMatrix()
// update with current values
for (var i = abcdef.length - 1; i >= 0; i--)
matrix[abcdef[i]] = this[abcdef[i]]
return matrix
}
// Convert matrix to string
, toString: function() {
return 'matrix(' + this.a + ',' + this.b + ',' + this.c + ',' + this.d + ',' + this.e + ',' + this.f + ')'
}
}
// Define parent
, parent: SVG.Element
// Add parent method
, construct: {
// Get current matrix
ctm: function() {
return new SVG.Matrix(this.node.getCTM())
},
// Get current screen matrix
screenCTM: function() {
/* https://bugzilla.mozilla.org/show_bug.cgi?id=1344537
This is needed because FF does not return the transformation matrix
for the inner coordinate system when getScreenCTM() is called on nested svgs.
However all other Browsers do that */
if(this instanceof SVG.Nested) {
var rect = this.rect(1,1)
var m = rect.node.getScreenCTM()
rect.remove()
return new SVG.Matrix(m)
}
return new SVG.Matrix(this.node.getScreenCTM())
}
}
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | 2 | SVG.extend(SVG.Element, {
// Remember arbitrary data
remember: function(k, v) {
// remember every item in an object individually
if (typeof arguments[0] == 'object')
for (var v in k)
this.remember(v, k[v])
// retrieve memory
else if (arguments.length == 1)
return this.memory()[k]
// store memory
else
this.memory()[k] = v
return this
}
// Erase a given memory
, forget: function() {
if (arguments.length == 0)
this._memory = {}
else
for (var i = arguments.length - 1; i >= 0; i--)
delete this.memory()[arguments[i]]
return this
}
// Initialize or return local memory object
, memory: function() {
return this._memory || (this._memory = {})
}
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 2 | SVG.Nested = SVG.invent({
// Initialize node
create: function() {
this.constructor.call(this, SVG.create('svg'))
this.style('overflow', 'visible')
}
// Inherit from
, inherit: SVG.Container
// Add parent method
, construct: {
// Create nested svg document
nested: function() {
return this.put(new SVG.Nested)
}
}
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 | 2 | // Module for unit convertions
SVG.Number = SVG.invent({
// Initialize
create: function(value, unit) {
// initialize defaults
this.value = 0
this.unit = unit || ''
// parse value
if (typeof value === 'number') {
// ensure a valid numeric value
this.value = isNaN(value) ? 0 : !isFinite(value) ? (value < 0 ? -3.4e+38 : +3.4e+38) : value
} else if (typeof value === 'string') {
unit = value.match(SVG.regex.numberAndUnit)
if (unit) {
// make value numeric
this.value = parseFloat(unit[1])
// normalize
if (unit[5] == '%')
this.value /= 100
else if (unit[5] == 's')
this.value *= 1000
// store unit
this.unit = unit[5]
}
} else {
if (value instanceof SVG.Number) {
this.value = value.valueOf()
this.unit = value.unit
}
}
}
// Add methods
, extend: {
// Stringalize
toString: function() {
return (
this.unit == '%' ?
~~(this.value * 1e8) / 1e6:
this.unit == 's' ?
this.value / 1e3 :
this.value
) + this.unit
}
, toJSON: function() {
return this.toString()
}
, // Convert to primitive
valueOf: function() {
return this.value
}
// Add number
, plus: function(number) {
number = new SVG.Number(number)
return new SVG.Number(this + number, this.unit || number.unit)
}
// Subtract number
, minus: function(number) {
number = new SVG.Number(number)
return new SVG.Number(this - number, this.unit || number.unit)
}
// Multiply number
, times: function(number) {
number = new SVG.Number(number)
return new SVG.Number(this * number, this.unit || number.unit)
}
// Divide number
, divide: function(number) {
number = new SVG.Number(number)
return new SVG.Number(this / number, this.unit || number.unit)
}
// Convert to different unit
, to: function(unit) {
var number = new SVG.Number(this)
if (typeof unit === 'string')
number.unit = unit
return number
}
// Make number morphable
, morph: function(number) {
this.destination = new SVG.Number(number)
if(number.relative) {
this.destination.value += this.value
}
return this
}
// Get morphed number at given position
, at: function(pos) {
// Make sure a destination is defined
if (!this.destination) return this
// Generate new morphed number
return new SVG.Number(this.destination)
.minus(this)
.times(pos)
.plus(this)
}
}
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 | 2 | SVG.Parent = SVG.invent({
// Initialize node
create: function(element) {
this.constructor.call(this, element)
}
// Inherit from
, inherit: SVG.Element
// Add class methods
, extend: {
// Returns all child elements
children: function() {
return SVG.utils.map(SVG.utils.filterSVGElements(this.node.childNodes), function(node) {
return SVG.adopt(node)
})
}
// Add given element at a position
, add: function(element, i) {
if (i == null)
this.node.appendChild(element.node)
else if (element.node != this.node.childNodes[i])
this.node.insertBefore(element.node, this.node.childNodes[i])
return this
}
// Basically does the same as `add()` but returns the added element instead
, put: function(element, i) {
this.add(element, i)
return element
}
// Checks if the given element is a child
, has: function(element) {
return this.index(element) >= 0
}
// Gets index of given element
, index: function(element) {
return [].slice.call(this.node.childNodes).indexOf(element.node)
}
// Get a element at the given index
, get: function(i) {
return SVG.adopt(this.node.childNodes[i])
}
// Get first child
, first: function() {
return this.get(0)
}
// Get the last child
, last: function() {
return this.get(this.node.childNodes.length - 1)
}
// Iterates over all children and invokes a given block
, each: function(block, deep) {
var i, il
, children = this.children()
for (i = 0, il = children.length; i < il; i++) {
if (children[i] instanceof SVG.Element)
block.apply(children[i], [i, children])
if (deep && (children[i] instanceof SVG.Container))
children[i].each(block, deep)
}
return this
}
// Remove a given child
, removeElement: function(element) {
this.node.removeChild(element.node)
return this
}
// Remove all elements in this container
, clear: function() {
// remove children
while(this.node.hasChildNodes())
this.node.removeChild(this.node.lastChild)
// remove defs reference
delete this._defs
return this
}
, // Get defs
defs: function() {
return this.doc().defs()
}
}
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | 2 | SVG.Path = SVG.invent({
// Initialize node
create: 'path'
// Inherit from
, inherit: SVG.Shape
// Add class methods
, extend: {
// Define morphable array
morphArray: SVG.PathArray
// Get array
, array: function() {
return this._array || (this._array = new SVG.PathArray(this.attr('d')))
}
// Plot new path
, plot: function(d) {
return (d == null) ?
this.array() :
this.clear().attr('d', typeof d == 'string' ? d : (this._array = new SVG.PathArray(d)))
}
// Clear array cache
, clear: function() {
delete this._array
return this
}
// Move by left top corner
, move: function(x, y) {
return this.attr('d', this.array().move(x, y))
}
// Move by left top corner over x-axis
, x: function(x) {
return x == null ? this.bbox().x : this.move(x, this.bbox().y)
}
// Move by left top corner over y-axis
, y: function(y) {
return y == null ? this.bbox().y : this.move(this.bbox().x, y)
}
// Set element size to given width and height
, size: function(width, height) {
var p = proportionalSize(this, width, height)
return this.attr('d', this.array().size(p.width, p.height))
}
// Set width of element
, width: function(width) {
return width == null ? this.bbox().width : this.size(width, this.bbox().height)
}
// Set height of element
, height: function(height) {
return height == null ? this.bbox().height : this.size(this.bbox().width, height)
}
}
// Add parent method
, construct: {
// Create a wrapped path element
path: function(d) {
// make sure plot is called as a setter
return this.put(new SVG.Path).plot(d || new SVG.PathArray)
}
}
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 | 2 2 2 20 20 2 | var pathHandlers = {
M: function(c, p, p0) {
p.x = p0.x = c[0]
p.y = p0.y = c[1]
return ['M', p.x, p.y]
},
L: function(c, p) {
p.x = c[0]
p.y = c[1]
return ['L', c[0], c[1]]
},
H: function(c, p) {
p.x = c[0]
return ['H', c[0]]
},
V: function(c, p) {
p.y = c[0]
return ['V', c[0]]
},
C: function(c, p) {
p.x = c[4]
p.y = c[5]
return ['C', c[0], c[1], c[2], c[3], c[4], c[5]]
},
S: function(c, p) {
p.x = c[2]
p.y = c[3]
return ['S', c[0], c[1], c[2], c[3]]
},
Q: function(c, p) {
p.x = c[2]
p.y = c[3]
return ['Q', c[0], c[1], c[2], c[3]]
},
T: function(c, p) {
p.x = c[0]
p.y = c[1]
return ['T', c[0], c[1]]
},
Z: function(c, p, p0) {
p.x = p0.x
p.y = p0.y
return ['Z']
},
A: function(c, p) {
p.x = c[5]
p.y = c[6]
return ['A', c[0], c[1], c[2], c[3], c[4], c[5], c[6]]
}
}
var mlhvqtcsa = 'mlhvqtcsaz'.split('')
for(var i = 0, il = mlhvqtcsa.length; i < il; ++i){
pathHandlers[mlhvqtcsa[i]] = (function(i){
return function(c, p, p0) {
if(i == 'H') c[0] = c[0] + p.x
else if(i == 'V') c[0] = c[0] + p.y
else if(i == 'A'){
c[5] = c[5] + p.x,
c[6] = c[6] + p.y
}
else
for(var j = 0, jl = c.length; j < jl; ++j) {
c[j] = c[j] + (j%2 ? p.y : p.x)
}
return pathHandlers[i](c, p, p0)
}
})(mlhvqtcsa[i].toUpperCase())
}
// Path points array
SVG.PathArray = function(array, fallback) {
SVG.Array.call(this, array, fallback || [['M', 0, 0]])
}
// Inherit from SVG.Array
SVG.PathArray.prototype = new SVG.Array
SVG.PathArray.prototype.constructor = SVG.PathArray
SVG.extend(SVG.PathArray, {
// Convert array to string
toString: function() {
return arrayToString(this.value)
}
// Move path string
, move: function(x, y) {
// get bounding box of current situation
var box = this.bbox()
// get relative offset
x -= box.x
y -= box.y
if (!isNaN(x) && !isNaN(y)) {
// move every point
for (var l, i = this.value.length - 1; i >= 0; i--) {
l = this.value[i][0]
if (l == 'M' || l == 'L' || l == 'T') {
this.value[i][1] += x
this.value[i][2] += y
} else if (l == 'H') {
this.value[i][1] += x
} else if (l == 'V') {
this.value[i][1] += y
} else if (l == 'C' || l == 'S' || l == 'Q') {
this.value[i][1] += x
this.value[i][2] += y
this.value[i][3] += x
this.value[i][4] += y
if (l == 'C') {
this.value[i][5] += x
this.value[i][6] += y
}
} else if (l == 'A') {
this.value[i][6] += x
this.value[i][7] += y
}
}
}
return this
}
// Resize path string
, size: function(width, height) {
// get bounding box of current situation
var i, l, box = this.bbox()
// recalculate position of all points according to new size
for (i = this.value.length - 1; i >= 0; i--) {
l = this.value[i][0]
if (l == 'M' || l == 'L' || l == 'T') {
this.value[i][1] = ((this.value[i][1] - box.x) * width) / box.width + box.x
this.value[i][2] = ((this.value[i][2] - box.y) * height) / box.height + box.y
} else if (l == 'H') {
this.value[i][1] = ((this.value[i][1] - box.x) * width) / box.width + box.x
} else if (l == 'V') {
this.value[i][1] = ((this.value[i][1] - box.y) * height) / box.height + box.y
} else if (l == 'C' || l == 'S' || l == 'Q') {
this.value[i][1] = ((this.value[i][1] - box.x) * width) / box.width + box.x
this.value[i][2] = ((this.value[i][2] - box.y) * height) / box.height + box.y
this.value[i][3] = ((this.value[i][3] - box.x) * width) / box.width + box.x
this.value[i][4] = ((this.value[i][4] - box.y) * height) / box.height + box.y
if (l == 'C') {
this.value[i][5] = ((this.value[i][5] - box.x) * width) / box.width + box.x
this.value[i][6] = ((this.value[i][6] - box.y) * height) / box.height + box.y
}
} else if (l == 'A') {
// resize radii
this.value[i][1] = (this.value[i][1] * width) / box.width
this.value[i][2] = (this.value[i][2] * height) / box.height
// move position values
this.value[i][6] = ((this.value[i][6] - box.x) * width) / box.width + box.x
this.value[i][7] = ((this.value[i][7] - box.y) * height) / box.height + box.y
}
}
return this
}
// Test if the passed path array use the same path data commands as this path array
, equalCommands: function(pathArray) {
var i, il, equalCommands
pathArray = new SVG.PathArray(pathArray)
equalCommands = this.value.length === pathArray.value.length
for(i = 0, il = this.value.length; equalCommands && i < il; i++) {
equalCommands = this.value[i][0] === pathArray.value[i][0]
}
return equalCommands
}
// Make path array morphable
, morph: function(pathArray) {
pathArray = new SVG.PathArray(pathArray)
if(this.equalCommands(pathArray)) {
this.destination = pathArray
} else {
this.destination = null
}
return this
}
// Get morphed path array at given position
, at: function(pos) {
// make sure a destination is defined
if (!this.destination) return this
var sourceArray = this.value
, destinationArray = this.destination.value
, array = [], pathArray = new SVG.PathArray()
, i, il, j, jl
// Animate has specified in the SVG spec
// See: https://www.w3.org/TR/SVG11/paths.html#PathElement
for (i = 0, il = sourceArray.length; i < il; i++) {
array[i] = [sourceArray[i][0]]
for(j = 1, jl = sourceArray[i].length; j < jl; j++) {
array[i][j] = sourceArray[i][j] + (destinationArray[i][j] - sourceArray[i][j]) * pos
}
// For the two flags of the elliptical arc command, the SVG spec say:
// Flags and booleans are interpolated as fractions between zero and one, with any non-zero value considered to be a value of one/true
// Elliptical arc command as an array followed by corresponding indexes:
// ['A', rx, ry, x-axis-rotation, large-arc-flag, sweep-flag, x, y]
// 0 1 2 3 4 5 6 7
if(array[i][0] === 'A') {
array[i][4] = +(array[i][4] != 0)
array[i][5] = +(array[i][5] != 0)
}
}
// Directly modify the value of a path array, this is done this way for performance
pathArray.value = array
return pathArray
}
// Absolutize and parse path to array
, parse: function(array) {
// if it's already a patharray, no need to parse it
if (array instanceof SVG.PathArray) return array.valueOf()
// prepare for parsing
var i, x0, y0, s, seg, arr
, x = 0
, y = 0
, paramCnt = { 'M':2, 'L':2, 'H':1, 'V':1, 'C':6, 'S':4, 'Q':4, 'T':2, 'A':7 }
if(typeof array == 'string'){
array = array
.replace(SVG.regex.numbersWithDots, pathRegReplace) // convert 45.123.123 to 45.123 .123
.replace(SVG.regex.pathLetters, ' $& ') // put some room between letters and numbers
.replace(SVG.regex.hyphen, '$1 -') // add space before hyphen
.trim() // trim
.split(SVG.regex.delimiter) // split into array
}else{
array = array.reduce(function(prev, curr){
return [].concat.call(prev, curr)
}, [])
}
// array now is an array containing all parts of a path e.g. ['M', '0', '0', 'L', '30', '30' ...]
var arr = []
, p = new SVG.Point()
, p0 = new SVG.Point()
, index = 0
, len = array.length
do{
// Test if we have a path letter
if(SVG.regex.isPathLetter.test(array[index])){
s = array[index]
++index
// If last letter was a move command and we got no new, it defaults to [L]ine
}else if(s == 'M'){
s = 'L'
}else if(s == 'm'){
s = 'l'
}
arr.push(pathHandlers[s].call(null,
array.slice(index, (index = index + paramCnt[s.toUpperCase()])).map(parseFloat),
p, p0
)
)
}while(len > index)
return arr
}
// Get bounding box of path
, bbox: function() {
SVG.parser.path.setAttribute('d', this.toString())
return SVG.parser.path.getBBox()
}
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | 2 | SVG.Pattern = SVG.invent({
// Initialize node
create: 'pattern'
// Inherit from
, inherit: SVG.Container
// Add class methods
, extend: {
// Return the fill id
fill: function() {
return 'url(#' + this.id() + ')'
}
// Update pattern by rebuilding
, update: function(block) {
// remove content
this.clear()
// invoke passed block
if (typeof block == 'function')
block.call(this, this)
return this
}
// Alias string convertion to fill
, toString: function() {
return this.fill()
}
// custom attr to handle transform
, attr: function(a, b, c) {
if(a == 'transform') a = 'patternTransform'
return SVG.Container.prototype.attr.call(this, a, b, c)
}
}
// Add parent method
, construct: {
// Create pattern element in defs
pattern: function(width, height, block) {
return this.defs().pattern(width, height, block)
}
}
})
SVG.extend(SVG.Defs, {
// Define gradient
pattern: function(width, height, block) {
return this.put(new SVG.Pattern).update(block).attr({
x: 0
, y: 0
, width: width
, height: height
, patternUnits: 'userSpaceOnUse'
})
}
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | 2 | SVG.Point = SVG.invent({
// Initialize
create: function(x,y) {
var i, source, base = {x:0, y:0}
// ensure source as object
source = Array.isArray(x) ?
{x:x[0], y:x[1]} :
typeof x === 'object' ?
{x:x.x, y:x.y} :
x != null ?
{x:x, y:(y != null ? y : x)} : base // If y has no value, then x is used has its value
// merge source
this.x = source.x
this.y = source.y
}
// Add methods
, extend: {
// Clone point
clone: function() {
return new SVG.Point(this)
}
// Morph one point into another
, morph: function(x, y) {
// store new destination
this.destination = new SVG.Point(x, y)
return this
}
// Get morphed point at a given position
, at: function(pos) {
// make sure a destination is defined
if (!this.destination) return this
// calculate morphed matrix at a given position
var point = new SVG.Point({
x: this.x + (this.destination.x - this.x) * pos
, y: this.y + (this.destination.y - this.y) * pos
})
return point
}
// Convert to native SVGPoint
, native: function() {
// create new point
var point = SVG.parser.native.createSVGPoint()
// update with current values
point.x = this.x
point.y = this.y
return point
}
// transform point with matrix
, transform: function(matrix) {
return new SVG.Point(this.native().matrixTransform(matrix.native()))
}
}
})
SVG.extend(SVG.Element, {
// Get point
point: function(x, y) {
return new SVG.Point(x,y).transform(this.screenCTM().inverse());
}
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 | 2 | // Poly points array SVG.PointArray = function(array, fallback) { SVG.Array.call(this, array, fallback || [[0,0]]) } // Inherit from SVG.Array SVG.PointArray.prototype = new SVG.Array SVG.PointArray.prototype.constructor = SVG.PointArray SVG.extend(SVG.PointArray, { // Convert array to string toString: function() { // convert to a poly point string for (var i = 0, il = this.value.length, array = []; i < il; i++) array.push(this.value[i].join(',')) return array.join(' ') } // Convert array to line object , toLine: function() { return { x1: this.value[0][0] , y1: this.value[0][1] , x2: this.value[1][0] , y2: this.value[1][1] } } // Get morphed array at given position , at: function(pos) { // make sure a destination is defined if (!this.destination) return this // generate morphed point string for (var i = 0, il = this.value.length, array = []; i < il; i++) array.push([ this.value[i][0] + (this.destination[i][0] - this.value[i][0]) * pos , this.value[i][1] + (this.destination[i][1] - this.value[i][1]) * pos ]) return new SVG.PointArray(array) } // Parse point string and flat array , parse: function(array) { var points = [] array = array.valueOf() // if it is an array if (Array.isArray(array)) { // and it is not flat, there is no need to parse it if(Array.isArray(array[0])) { return array } } else { // Else, it is considered as a string // parse points array = array.trim().split(SVG.regex.delimiter).map(parseFloat) } // validate points - https://svgwg.org/svg2-draft/shapes.html#DataTypePoints // Odd number of coordinates is an error. In such cases, drop the last odd coordinate. if (array.length % 2 !== 0) array.pop() // wrap points in two-tuples and parse points as floats for(var i = 0, len = array.length; i < len; i = i + 2) points.push([ array[i], array[i+1] ]) return points } // Move point string , move: function(x, y) { var box = this.bbox() // get relative offset x -= box.x y -= box.y // move every point if (!isNaN(x) && !isNaN(y)) for (var i = this.value.length - 1; i >= 0; i--) this.value[i] = [this.value[i][0] + x, this.value[i][1] + y] return this } // Resize poly string , size: function(width, height) { var i, box = this.bbox() // recalculate position of all points according to new size for (i = this.value.length - 1; i >= 0; i--) { if(box.width) this.value[i][0] = ((this.value[i][0] - box.x) * width) / box.width + box.x if(box.height) this.value[i][1] = ((this.value[i][1] - box.y) * height) / box.height + box.y } return this } // Get bounding box of points , bbox: function() { SVG.parser.poly.setAttribute('points', this.toString()) return SVG.parser.poly.getBBox() } }) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 2 | // unify all point to point elements
SVG.extend(SVG.Line, SVG.Polyline, SVG.Polygon, {
// Define morphable array
morphArray: SVG.PointArray
// Move by left top corner over x-axis
, x: function(x) {
return x == null ? this.bbox().x : this.move(x, this.bbox().y)
}
// Move by left top corner over y-axis
, y: function(y) {
return y == null ? this.bbox().y : this.move(this.bbox().x, y)
}
// Set width of element
, width: function(width) {
var b = this.bbox()
return width == null ? b.width : this.size(width, b.height)
}
// Set height of element
, height: function(height) {
var b = this.bbox()
return height == null ? b.height : this.size(b.width, height)
}
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | 2 | SVG.Polyline = SVG.invent({
// Initialize node
create: 'polyline'
// Inherit from
, inherit: SVG.Shape
// Add parent method
, construct: {
// Create a wrapped polyline element
polyline: function(p) {
// make sure plot is called as a setter
return this.put(new SVG.Polyline).plot(p || new SVG.PointArray)
}
}
})
SVG.Polygon = SVG.invent({
// Initialize node
create: 'polygon'
// Inherit from
, inherit: SVG.Shape
// Add parent method
, construct: {
// Create a wrapped polygon element
polygon: function(p) {
// make sure plot is called as a setter
return this.put(new SVG.Polygon).plot(p || new SVG.PointArray)
}
}
})
// Add polygon-specific functions
SVG.extend(SVG.Polyline, SVG.Polygon, {
// Get array
array: function() {
return this._array || (this._array = new SVG.PointArray(this.attr('points')))
}
// Plot new path
, plot: function(p) {
return (p == null) ?
this.array() :
this.clear().attr('points', typeof p == 'string' ? p : (this._array = new SVG.PointArray(p)))
}
// Clear array cache
, clear: function() {
delete this._array
return this
}
// Move by left top corner
, move: function(x, y) {
return this.attr('points', this.array().move(x, y))
}
// Set element size to given width and height
, size: function(width, height) {
var p = proportionalSize(this, width, height)
return this.attr('points', this.array().size(p.width, p.height))
}
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | 2 | // Add CustomEvent to IE9 and IE10
if (typeof window.CustomEvent !== 'function') {
// Code from: https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent
var CustomEvent = function(event, options) {
options = options || { bubbles: false, cancelable: false, detail: undefined }
var e = document.createEvent('CustomEvent')
e.initCustomEvent(event, options.bubbles, options.cancelable, options.detail)
return e
}
CustomEvent.prototype = window.Event.prototype
window.CustomEvent = CustomEvent
}
// requestAnimationFrame / cancelAnimationFrame Polyfill with fallback based on Paul Irish
(function(w) {
var lastTime = 0
var vendors = ['moz', 'webkit']
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
w.requestAnimationFrame = w[vendors[x] + 'RequestAnimationFrame']
w.cancelAnimationFrame = w[vendors[x] + 'CancelAnimationFrame'] ||
w[vendors[x] + 'CancelRequestAnimationFrame']
}
w.requestAnimationFrame = w.requestAnimationFrame ||
function(callback) {
var currTime = new Date().getTime()
var timeToCall = Math.max(0, 16 - (currTime - lastTime))
var id = w.setTimeout(function() {
callback(currTime + timeToCall)
}, timeToCall)
lastTime = currTime + timeToCall
return id
}
w.cancelAnimationFrame = w.cancelAnimationFrame || w.clearTimeout;
}(window))
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 2 | SVG.Rect = SVG.invent({
// Initialize node
create: 'rect'
// Inherit from
, inherit: SVG.Shape
// Add parent method
, construct: {
// Create a rect element
rect: function(width, height) {
return this.put(new SVG.Rect()).size(width, height)
}
}
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | 2 | // Storage for regular expressions
SVG.regex = {
// Parse unit value
numberAndUnit: /^([+-]?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?)([a-z%]*)$/i
// Parse hex value
, hex: /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i
// Parse rgb value
, rgb: /rgb\((\d+),(\d+),(\d+)\)/
// Parse reference id
, reference: /#([a-z0-9\-_]+)/i
// splits a transformation chain
, transforms: /\)\s*,?\s*/
// Whitespace
, whitespace: /\s/g
// Test hex value
, isHex: /^#[a-f0-9]{3,6}$/i
// Test rgb value
, isRgb: /^rgb\(/
// Test css declaration
, isCss: /[^:]+:[^;]+;?/
// Test for blank string
, isBlank: /^(\s+)?$/
// Test for numeric string
, isNumber: /^[+-]?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i
// Test for percent value
, isPercent: /^-?[\d\.]+%$/
// Test for image url
, isImage: /\.(jpg|jpeg|png|gif|svg)(\?[^=]+.*)?/i
// split at whitespace and comma
, delimiter: /[\s,]+/
// The following regex are used to parse the d attribute of a path
// Matches all hyphens which are not after an exponent
, hyphen: /([^e])\-/gi
// Replaces and tests for all path letters
, pathLetters: /[MLHVCSQTAZ]/gi
// yes we need this one, too
, isPathLetter: /[MLHVCSQTAZ]/i
// matches 0.154.23.45
, numbersWithDots: /((\d?\.\d+(?:e[+-]?\d+)?)((?:\.\d+(?:e[+-]?\d+)?)+))+/gi
// matches .
, dots: /\./g
}
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 2 | // Method for getting an element by id SVG.get = function(id) { var node = document.getElementById(idFromReference(id) || id) return SVG.adopt(node) } // Select elements by query string SVG.select = function(query, parent) { return new SVG.Set( SVG.utils.map((parent || document).querySelectorAll(query), function(node) { return SVG.adopt(node) }) ) } SVG.extend(SVG.Parent, { // Scoped select method select: function(query) { return SVG.select(query, this.node) } }) |
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 | 2 | SVG.Set = SVG.invent({
// Initialize
create: function(members) {
// Set initial state
Array.isArray(members) ? this.members = members : this.clear()
}
// Add class methods
, extend: {
// Add element to set
add: function() {
var i, il, elements = [].slice.call(arguments)
for (i = 0, il = elements.length; i < il; i++)
this.members.push(elements[i])
return this
}
// Remove element from set
, remove: function(element) {
var i = this.index(element)
// remove given child
if (i > -1)
this.members.splice(i, 1)
return this
}
// Iterate over all members
, each: function(block) {
for (var i = 0, il = this.members.length; i < il; i++)
block.apply(this.members[i], [i, this.members])
return this
}
// Restore to defaults
, clear: function() {
// initialize store
this.members = []
return this
}
// Get the length of a set
, length: function() {
return this.members.length
}
// Checks if a given element is present in set
, has: function(element) {
return this.index(element) >= 0
}
// retuns index of given element in set
, index: function(element) {
return this.members.indexOf(element)
}
// Get member at given index
, get: function(i) {
return this.members[i]
}
// Get first member
, first: function() {
return this.get(0)
}
// Get last member
, last: function() {
return this.get(this.members.length - 1)
}
// Default value
, valueOf: function() {
return this.members
}
// Get the bounding box of all members included or empty box if set has no items
, bbox: function(){
// return an empty box of there are no members
if (this.members.length == 0)
return new SVG.RBox()
// get the first rbox and update the target bbox
var rbox = this.members[0].rbox(this.members[0].doc())
this.each(function() {
// user rbox for correct position and visual representation
rbox = rbox.merge(this.rbox(this.doc()))
})
return rbox
}
}
// Add parent method
, construct: {
// Create a new set
set: function(members) {
return new SVG.Set(members)
}
}
})
SVG.FX.Set = SVG.invent({
// Initialize node
create: function(set) {
// store reference to set
this.set = set
}
})
// Alias methods
SVG.Set.inherit = function() {
var m
, methods = []
// gather shape methods
for(var m in SVG.Shape.prototype)
if (typeof SVG.Shape.prototype[m] == 'function' && typeof SVG.Set.prototype[m] != 'function')
methods.push(m)
// apply shape aliasses
methods.forEach(function(method) {
SVG.Set.prototype[method] = function() {
for (var i = 0, il = this.members.length; i < il; i++)
if (this.members[i] && typeof this.members[i][method] == 'function')
this.members[i][method].apply(this.members[i], arguments)
return method == 'animate' ? (this.fx || (this.fx = new SVG.FX.Set(this))) : this
}
})
// clear methods for the next round
methods = []
// gather fx methods
for(var m in SVG.FX.prototype)
if (typeof SVG.FX.prototype[m] == 'function' && typeof SVG.FX.Set.prototype[m] != 'function')
methods.push(m)
// apply fx aliasses
methods.forEach(function(method) {
SVG.FX.Set.prototype[method] = function() {
for (var i = 0, il = this.set.members.length; i < il; i++)
this.set.members[i].fx[method].apply(this.set.members[i].fx, arguments)
return this
}
})
}
|
| 1 2 3 4 5 6 7 8 9 10 11 | 2 | SVG.Shape = SVG.invent({
// Initialize node
create: function(element) {
this.constructor.call(this, element)
}
// Inherit from
, inherit: SVG.Element
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | 2 | SVG.extend(SVG.Element, {
// Dynamic style generator
style: function(s, v) {
if (arguments.length == 0) {
// get full style
return this.node.style.cssText || ''
} else if (arguments.length < 2) {
// apply every style individually if an object is passed
if (typeof s == 'object') {
for (v in s) this.style(v, s[v])
} else if (SVG.regex.isCss.test(s)) {
// parse css string
s = s.split(/\s*;\s*/)
// filter out suffix ; and stuff like ;;
.filter(function(e) { return !!e })
.map(function(e){ return e.split(/\s*:\s*/) })
// apply every definition individually
while (v = s.pop()) {
this.style(v[0], v[1])
}
} else {
// act as a getter if the first and only argument is not an object
return this.node.style[camelCase(s)]
}
} else {
this.node.style[camelCase(s)] = v === null || SVG.regex.isBlank.test(v) ? '' : v
}
return this
}
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 | 2 2 2 2 2 | // Define list of available attributes for stroke and fill
var sugar = {
stroke: ['color', 'width', 'opacity', 'linecap', 'linejoin', 'miterlimit', 'dasharray', 'dashoffset']
, fill: ['color', 'opacity', 'rule']
, prefix: function(t, a) {
return a == 'color' ? t : t + '-' + a
}
}
// Add sugar for fill and stroke
;['fill', 'stroke'].forEach(function(m) {
var i, extension = {}
extension[m] = function(o) {
if (typeof o == 'undefined')
return this
if (typeof o == 'string' || SVG.Color.isRgb(o) || (o && typeof o.fill === 'function'))
this.attr(m, o)
else
// set all attributes from sugar.fill and sugar.stroke list
for (i = sugar[m].length - 1; i >= 0; i--)
if (o[sugar[m][i]] != null)
this.attr(sugar.prefix(m, sugar[m][i]), o[sugar[m][i]])
return this
}
SVG.extend(SVG.Element, SVG.FX, extension)
})
SVG.extend(SVG.Element, SVG.FX, {
// Map rotation to transform
rotate: function(d, cx, cy) {
return this.transform({ rotation: d, cx: cx, cy: cy })
}
// Map skew to transform
, skew: function(x, y, cx, cy) {
return arguments.length == 1 || arguments.length == 3 ?
this.transform({ skew: x, cx: y, cy: cx }) :
this.transform({ skewX: x, skewY: y, cx: cx, cy: cy })
}
// Map scale to transform
, scale: function(x, y, cx, cy) {
return arguments.length == 1 || arguments.length == 3 ?
this.transform({ scale: x, cx: y, cy: cx }) :
this.transform({ scaleX: x, scaleY: y, cx: cx, cy: cy })
}
// Map translate to transform
, translate: function(x, y) {
return this.transform({ x: x, y: y })
}
// Map flip to transform
, flip: function(a, o) {
o = typeof a == 'number' ? a : o
return this.transform({ flip: a || 'both', offset: o })
}
// Map matrix to transform
, matrix: function(m) {
return this.attr('transform', new SVG.Matrix(arguments.length == 6 ? [].slice.call(arguments) : m))
}
// Opacity
, opacity: function(value) {
return this.attr('opacity', value)
}
// Relative move over x axis
, dx: function(x) {
return this.x(new SVG.Number(x).plus(this instanceof SVG.FX ? 0 : this.x()), true)
}
// Relative move over y axis
, dy: function(y) {
return this.y(new SVG.Number(y).plus(this instanceof SVG.FX ? 0 : this.y()), true)
}
// Relative move over x and y axes
, dmove: function(x, y) {
return this.dx(x).dy(y)
}
})
SVG.extend(SVG.Rect, SVG.Ellipse, SVG.Circle, SVG.Gradient, SVG.FX, {
// Add x and y radius
radius: function(x, y) {
var type = (this._target || this).type;
return type == 'radial' || type == 'circle' ?
this.attr('r', new SVG.Number(x)) :
this.rx(x).ry(y == null ? x : y)
}
})
SVG.extend(SVG.Path, {
// Get path length
length: function() {
return this.node.getTotalLength()
}
// Get point at length
, pointAt: function(length) {
return this.node.getPointAtLength(length)
}
})
SVG.extend(SVG.Parent, SVG.Text, SVG.Tspan, SVG.FX, {
// Set font
font: function(a, v) {
if (typeof a == 'object') {
for (v in a) this.font(v, a[v])
}
return a == 'leading' ?
this.leading(v) :
a == 'anchor' ?
this.attr('text-anchor', v) :
a == 'size' || a == 'family' || a == 'weight' || a == 'stretch' || a == 'variant' || a == 'style' ?
this.attr('font-'+ a, v) :
this.attr(a, v)
}
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 2 | SVG.Symbol = SVG.invent({
// Initialize node
create: 'symbol'
// Inherit from
, inherit: SVG.Container
, construct: {
// create symbol
symbol: function() {
return this.put(new SVG.Symbol)
}
}
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 | 2 | SVG.Text = SVG.invent({
// Initialize node
create: function() {
this.constructor.call(this, SVG.create('text'))
this.dom.leading = new SVG.Number(1.3) // store leading value for rebuilding
this._rebuild = true // enable automatic updating of dy values
this._build = false // disable build mode for adding multiple lines
// set default font
this.attr('font-family', SVG.defaults.attrs['font-family'])
}
// Inherit from
, inherit: SVG.Shape
// Add class methods
, extend: {
// Move over x-axis
x: function(x) {
// act as getter
if (x == null)
return this.attr('x')
return this.attr('x', x)
}
// Move over y-axis
, y: function(y) {
var oy = this.attr('y')
, o = typeof oy === 'number' ? oy - this.bbox().y : 0
// act as getter
if (y == null)
return typeof oy === 'number' ? oy - o : oy
return this.attr('y', typeof y === 'number' ? y + o : y)
}
// Move center over x-axis
, cx: function(x) {
return x == null ? this.bbox().cx : this.x(x - this.bbox().width / 2)
}
// Move center over y-axis
, cy: function(y) {
return y == null ? this.bbox().cy : this.y(y - this.bbox().height / 2)
}
// Set the text content
, text: function(text) {
// act as getter
if (typeof text === 'undefined'){
var text = ''
var children = this.node.childNodes
for(var i = 0, len = children.length; i < len; ++i){
// add newline if its not the first child and newLined is set to true
if(i != 0 && children[i].nodeType != 3 && SVG.adopt(children[i]).dom.newLined == true){
text += '\n'
}
// add content of this node
text += children[i].textContent
}
return text
}
// remove existing content
this.clear().build(true)
if (typeof text === 'function') {
// call block
text.call(this, this)
} else {
// store text and make sure text is not blank
text = text.split('\n')
// build new lines
for (var i = 0, il = text.length; i < il; i++)
this.tspan(text[i]).newLine()
}
// disable build mode and rebuild lines
return this.build(false).rebuild()
}
// Set font size
, size: function(size) {
return this.attr('font-size', size).rebuild()
}
// Set / get leading
, leading: function(value) {
// act as getter
if (value == null)
return this.dom.leading
// act as setter
this.dom.leading = new SVG.Number(value)
return this.rebuild()
}
// Get all the first level lines
, lines: function() {
var node = (this.textPath && this.textPath() || this).node
// filter tspans and map them to SVG.js instances
var lines = SVG.utils.map(SVG.utils.filterSVGElements(node.childNodes), function(el){
return SVG.adopt(el)
})
// return an instance of SVG.set
return new SVG.Set(lines)
}
// Rebuild appearance type
, rebuild: function(rebuild) {
// store new rebuild flag if given
if (typeof rebuild == 'boolean')
this._rebuild = rebuild
// define position of all lines
if (this._rebuild) {
var self = this
, blankLineOffset = 0
, dy = this.dom.leading * new SVG.Number(this.attr('font-size'))
this.lines().each(function() {
if (this.dom.newLined) {
if (!self.textPath())
this.attr('x', self.attr('x'))
if(this.text() == '\n') {
blankLineOffset += dy
}else{
this.attr('dy', dy + blankLineOffset)
blankLineOffset = 0
}
}
})
this.fire('rebuild')
}
return this
}
// Enable / disable build mode
, build: function(build) {
this._build = !!build
return this
}
// overwrite method from parent to set data properly
, setData: function(o){
this.dom = o
this.dom.leading = new SVG.Number(o.leading || 1.3)
return this
}
}
// Add parent method
, construct: {
// Create text element
text: function(text) {
return this.put(new SVG.Text).text(text)
}
// Create plain text element
, plain: function(text) {
return this.put(new SVG.Text).plain(text)
}
}
})
SVG.Tspan = SVG.invent({
// Initialize node
create: 'tspan'
// Inherit from
, inherit: SVG.Shape
// Add class methods
, extend: {
// Set text content
text: function(text) {
if(text == null) return this.node.textContent + (this.dom.newLined ? '\n' : '')
typeof text === 'function' ? text.call(this, this) : this.plain(text)
return this
}
// Shortcut dx
, dx: function(dx) {
return this.attr('dx', dx)
}
// Shortcut dy
, dy: function(dy) {
return this.attr('dy', dy)
}
// Create new line
, newLine: function() {
// fetch text parent
var t = this.parent(SVG.Text)
// mark new line
this.dom.newLined = true
// apply new hy¡n
return this.dy(t.dom.leading * t.attr('font-size')).attr('x', t.x())
}
}
})
SVG.extend(SVG.Text, SVG.Tspan, {
// Create plain text node
plain: function(text) {
// clear if build mode is disabled
if (this._build === false)
this.clear()
// create text node
this.node.appendChild(document.createTextNode(text))
return this
}
// Create a tspan
, tspan: function(text) {
var node = (this.textPath && this.textPath() || this).node
, tspan = new SVG.Tspan
// clear if build mode is disabled
if (this._build === false)
this.clear()
// add new tspan
node.appendChild(tspan.node)
return tspan.text(text)
}
// Clear all lines
, clear: function() {
var node = (this.textPath && this.textPath() || this).node
// remove existing child nodes
while (node.hasChildNodes())
node.removeChild(node.lastChild)
return this
}
// Get length of text element
, length: function() {
return this.node.getComputedTextLength()
}
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | 2 | SVG.TextPath = SVG.invent({
// Initialize node
create: 'textPath'
// Inherit from
, inherit: SVG.Parent
// Define parent class
, parent: SVG.Text
// Add parent method
, construct: {
// Create path for text to run on
path: function(d) {
// create textPath element
var path = new SVG.TextPath
, track = this.doc().defs().path(d)
// move lines to textpath
while (this.node.hasChildNodes())
path.node.appendChild(this.node.firstChild)
// add textPath element as child node
this.node.appendChild(path.node)
// link textPath to path and add content
path.attr('href', '#' + track, SVG.xlink)
return this
}
// return the array of the path track element
, array: function() {
var track = this.track()
return track ? track.array() : null
}
// Plot path if any
, plot: function(d) {
var track = this.track()
, pathArray = null
if (track) {
pathArray = track.plot(d)
}
return (d == null) ? pathArray : this
}
// Get the path track element
, track: function() {
var path = this.textPath()
if (path)
return path.reference('href')
}
// Get the textPath child
, textPath: function() {
if (this.node.firstChild && this.node.firstChild.nodeName == 'textPath')
return SVG.adopt(this.node.firstChild)
}
}
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 | 2 | SVG.extend(SVG.Element, {
// Add transformations
transform: function(o, relative) {
// get target in case of the fx module, otherwise reference this
var target = this
, matrix, bbox
// act as a getter
if (typeof o !== 'object') {
// get current matrix
matrix = new SVG.Matrix(target).extract()
return typeof o === 'string' ? matrix[o] : matrix
}
// get current matrix
matrix = new SVG.Matrix(target)
// ensure relative flag
relative = !!relative || !!o.relative
// act on matrix
if (o.a != null) {
matrix = relative ?
// relative
matrix.multiply(new SVG.Matrix(o)) :
// absolute
new SVG.Matrix(o)
// act on rotation
} else if (o.rotation != null) {
// ensure centre point
ensureCentre(o, target)
// apply transformation
matrix = relative ?
// relative
matrix.rotate(o.rotation, o.cx, o.cy) :
// absolute
matrix.rotate(o.rotation - matrix.extract().rotation, o.cx, o.cy)
// act on scale
} else if (o.scale != null || o.scaleX != null || o.scaleY != null) {
// ensure centre point
ensureCentre(o, target)
// ensure scale values on both axes
o.scaleX = o.scale != null ? o.scale : o.scaleX != null ? o.scaleX : 1
o.scaleY = o.scale != null ? o.scale : o.scaleY != null ? o.scaleY : 1
if (!relative) {
// absolute; multiply inversed values
var e = matrix.extract()
o.scaleX = o.scaleX * 1 / e.scaleX
o.scaleY = o.scaleY * 1 / e.scaleY
}
matrix = matrix.scale(o.scaleX, o.scaleY, o.cx, o.cy)
// act on skew
} else if (o.skew != null || o.skewX != null || o.skewY != null) {
// ensure centre point
ensureCentre(o, target)
// ensure skew values on both axes
o.skewX = o.skew != null ? o.skew : o.skewX != null ? o.skewX : 0
o.skewY = o.skew != null ? o.skew : o.skewY != null ? o.skewY : 0
if (!relative) {
// absolute; reset skew values
var e = matrix.extract()
matrix = matrix.multiply(new SVG.Matrix().skew(e.skewX, e.skewY, o.cx, o.cy).inverse())
}
matrix = matrix.skew(o.skewX, o.skewY, o.cx, o.cy)
// act on flip
} else if (o.flip) {
if(o.flip == 'x' || o.flip == 'y') {
o.offset = o.offset == null ? target.bbox()['c' + o.flip] : o.offset
} else {
if(o.offset == null) {
bbox = target.bbox()
o.flip = bbox.cx
o.offset = bbox.cy
} else {
o.flip = o.offset
}
}
matrix = new SVG.Matrix().flip(o.flip, o.offset)
// act on translate
} else if (o.x != null || o.y != null) {
if (relative) {
// relative
matrix = matrix.translate(o.x, o.y)
} else {
// absolute
if (o.x != null) matrix.e = o.x
if (o.y != null) matrix.f = o.y
}
}
return this.attr('transform', matrix)
}
})
SVG.extend(SVG.FX, {
transform: function(o, relative) {
// get target in case of the fx module, otherwise reference this
var target = this.target()
, matrix, bbox
// act as a getter
if (typeof o !== 'object') {
// get current matrix
matrix = new SVG.Matrix(target).extract()
return typeof o === 'string' ? matrix[o] : matrix
}
// ensure relative flag
relative = !!relative || !!o.relative
// act on matrix
if (o.a != null) {
matrix = new SVG.Matrix(o)
// act on rotation
} else if (o.rotation != null) {
// ensure centre point
ensureCentre(o, target)
// apply transformation
matrix = new SVG.Rotate(o.rotation, o.cx, o.cy)
// act on scale
} else if (o.scale != null || o.scaleX != null || o.scaleY != null) {
// ensure centre point
ensureCentre(o, target)
// ensure scale values on both axes
o.scaleX = o.scale != null ? o.scale : o.scaleX != null ? o.scaleX : 1
o.scaleY = o.scale != null ? o.scale : o.scaleY != null ? o.scaleY : 1
matrix = new SVG.Scale(o.scaleX, o.scaleY, o.cx, o.cy)
// act on skew
} else if (o.skewX != null || o.skewY != null) {
// ensure centre point
ensureCentre(o, target)
// ensure skew values on both axes
o.skewX = o.skewX != null ? o.skewX : 0
o.skewY = o.skewY != null ? o.skewY : 0
matrix = new SVG.Skew(o.skewX, o.skewY, o.cx, o.cy)
// act on flip
} else if (o.flip) {
if(o.flip == 'x' || o.flip == 'y') {
o.offset = o.offset == null ? target.bbox()['c' + o.flip] : o.offset
} else {
if(o.offset == null) {
bbox = target.bbox()
o.flip = bbox.cx
o.offset = bbox.cy
} else {
o.flip = o.offset
}
}
matrix = new SVG.Matrix().flip(o.flip, o.offset)
// act on translate
} else if (o.x != null || o.y != null) {
matrix = new SVG.Translate(o.x, o.y)
}
if(!matrix) return this
matrix.relative = relative
this.last().transforms.push(matrix)
return this._callStart()
}
})
SVG.extend(SVG.Element, {
// Reset all transformations
untransform: function() {
return this.attr('transform', null)
},
// merge the whole transformation chain into one matrix and returns it
matrixify: function() {
var matrix = (this.attr('transform') || '')
// split transformations
.split(SVG.regex.transforms).slice(0,-1).map(function(str){
// generate key => value pairs
var kv = str.trim().split('(')
return [kv[0], kv[1].split(SVG.regex.delimiter).map(function(str){ return parseFloat(str) })]
})
// merge every transformation into one matrix
.reduce(function(matrix, transform){
if(transform[0] == 'matrix') return matrix.multiply(arrayToMatrix(transform[1]))
return matrix[transform[0]].apply(matrix, transform[1])
}, new SVG.Matrix())
return matrix
},
// add an element to another parent without changing the visual representation on the screen
toParent: function(parent) {
if(this == parent) return this
var ctm = this.screenCTM()
var pCtm = parent.screenCTM().inverse()
this.addTo(parent).untransform().transform(pCtm.multiply(ctm))
return this
},
// same as above with parent equals root-svg
toDoc: function() {
return this.toParent(this.doc())
}
})
SVG.Transformation = SVG.invent({
create: function(source, inversed){
if(arguments.length > 1 && typeof inversed != 'boolean'){
return this.constructor.call(this, [].slice.call(arguments))
}
if(Array.isArray(source)){
for(var i = 0, len = this.arguments.length; i < len; ++i){
this[this.arguments[i]] = source[i]
}
} else if(typeof source == 'object'){
for(var i = 0, len = this.arguments.length; i < len; ++i){
this[this.arguments[i]] = source[this.arguments[i]]
}
}
this.inversed = false
if(inversed === true){
this.inversed = true
}
}
, extend: {
arguments: []
, method: ''
, at: function(pos){
var params = []
for(var i = 0, len = this.arguments.length; i < len; ++i){
params.push(this[this.arguments[i]])
}
var m = this._undo || new SVG.Matrix()
m = new SVG.Matrix().morph(SVG.Matrix.prototype[this.method].apply(m, params)).at(pos)
return this.inversed ? m.inverse() : m
}
, undo: function(o){
for(var i = 0, len = this.arguments.length; i < len; ++i){
o[this.arguments[i]] = typeof this[this.arguments[i]] == 'undefined' ? 0 : o[this.arguments[i]]
}
// The method SVG.Matrix.extract which was used before calling this
// method to obtain a value for the parameter o doesn't return a cx and
// a cy so we use the ones that were provided to this object at its creation
o.cx = this.cx
o.cy = this.cy
this._undo = new SVG[capitalize(this.method)](o, true).at(1)
return this
}
}
})
SVG.Translate = SVG.invent({
parent: SVG.Matrix
, inherit: SVG.Transformation
, create: function(source, inversed){
this.constructor.apply(this, [].slice.call(arguments))
}
, extend: {
arguments: ['transformedX', 'transformedY']
, method: 'translate'
}
})
SVG.Rotate = SVG.invent({
parent: SVG.Matrix
, inherit: SVG.Transformation
, create: function(source, inversed){
this.constructor.apply(this, [].slice.call(arguments))
}
, extend: {
arguments: ['rotation', 'cx', 'cy']
, method: 'rotate'
, at: function(pos){
var m = new SVG.Matrix().rotate(new SVG.Number().morph(this.rotation - (this._undo ? this._undo.rotation : 0)).at(pos), this.cx, this.cy)
return this.inversed ? m.inverse() : m
}
, undo: function(o){
this._undo = o
return this
}
}
})
SVG.Scale = SVG.invent({
parent: SVG.Matrix
, inherit: SVG.Transformation
, create: function(source, inversed){
this.constructor.apply(this, [].slice.call(arguments))
}
, extend: {
arguments: ['scaleX', 'scaleY', 'cx', 'cy']
, method: 'scale'
}
})
SVG.Skew = SVG.invent({
parent: SVG.Matrix
, inherit: SVG.Transformation
, create: function(source, inversed){
this.constructor.apply(this, [].slice.call(arguments))
}
, extend: {
arguments: ['skewX', 'skewY', 'cx', 'cy']
, method: 'skew'
}
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | 2 | SVG.extend(SVG.Parent, {
ungroup: function(parent, depth) {
if(depth === 0 || this instanceof SVG.Defs || this.node == SVG.parser.draw) return this
parent = parent || (this instanceof SVG.Doc ? this : this.parent(SVG.Parent))
depth = depth || Infinity
this.each(function(){
if(this instanceof SVG.Defs) return this
if(this instanceof SVG.Parent) return this.ungroup(parent, depth-1)
return this.toParent(parent)
})
this.node.firstChild || this.remove()
return this
},
flatten: function(parent, depth) {
return this.ungroup(parent, depth)
}
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | 2 | SVG.Use = SVG.invent({
// Initialize node
create: 'use'
// Inherit from
, inherit: SVG.Shape
// Add class methods
, extend: {
// Use element as a reference
element: function(element, file) {
// Set lined element
return this.attr('href', (file || '') + '#' + element, SVG.xlink)
}
}
// Add parent method
, construct: {
// Create a use element
use: function(element, file) {
return this.put(new SVG.Use).element(element, file)
}
}
})
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | 2 | SVG.utils = {
// Map function
map: function(array, block) {
var i
, il = array.length
, result = []
for (i = 0; i < il; i++)
result.push(block(array[i]))
return result
}
// Filter function
, filter: function(array, block) {
var i
, il = array.length
, result = []
for (i = 0; i < il; i++)
if (block(array[i]))
result.push(array[i])
return result
}
// Degrees to radians
, radians: function(d) {
return d % 360 * Math.PI / 180
}
// Radians to degrees
, degrees: function(r) {
return r * 180 / Math.PI % 360
}
, filterSVGElements: function(nodes) {
return this.filter( nodes, function(el) { return el instanceof window.SVGElement })
}
}
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 | 2 |
SVG.ViewBox = SVG.invent({
create: function(source) {
var i, base = [0, 0, 0, 0]
var x, y, width, height, box, view, we, he
, wm = 1 // width multiplier
, hm = 1 // height multiplier
, reg = /[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?/gi
if(source instanceof SVG.Element){
we = source
he = source
view = (source.attr('viewBox') || '').match(reg)
box = source.bbox
// get dimensions of current node
width = new SVG.Number(source.width())
height = new SVG.Number(source.height())
// find nearest non-percentual dimensions
while (width.unit == '%') {
wm *= width.value
width = new SVG.Number(we instanceof SVG.Doc ? we.parent().offsetWidth : we.parent().width())
we = we.parent()
}
while (height.unit == '%') {
hm *= height.value
height = new SVG.Number(he instanceof SVG.Doc ? he.parent().offsetHeight : he.parent().height())
he = he.parent()
}
// ensure defaults
this.x = 0
this.y = 0
this.width = width * wm
this.height = height * hm
this.zoom = 1
if (view) {
// get width and height from viewbox
x = parseFloat(view[0])
y = parseFloat(view[1])
width = parseFloat(view[2])
height = parseFloat(view[3])
// calculate zoom accoring to viewbox
this.zoom = ((this.width / this.height) > (width / height)) ?
this.height / height :
this.width / width
// calculate real pixel dimensions on parent SVG.Doc element
this.x = x
this.y = y
this.width = width
this.height = height
}
}else{
// ensure source as object
source = typeof source === 'string' ?
source.match(reg).map(function(el){ return parseFloat(el) }) :
Array.isArray(source) ?
source :
typeof source == 'object' ?
[source.x, source.y, source.width, source.height] :
arguments.length == 4 ?
[].slice.call(arguments) :
base
this.x = source[0]
this.y = source[1]
this.width = source[2]
this.height = source[3]
}
}
, extend: {
toString: function() {
return this.x + ' ' + this.y + ' ' + this.width + ' ' + this.height
}
, morph: function(x, y, width, height){
this.destination = new SVG.ViewBox(x, y, width, height)
return this
}
, at: function(pos) {
if(!this.destination) return this
return new SVG.ViewBox([
this.x + (this.destination.x - this.x) * pos
, this.y + (this.destination.y - this.y) * pos
, this.width + (this.destination.width - this.width) * pos
, this.height + (this.destination.height - this.height) * pos
])
}
}
// Define parent
, parent: SVG.Container
// Add parent method
, construct: {
// get/set viewbox
viewbox: function(x, y, width, height) {
if (arguments.length == 0)
// act as a getter if there are no arguments
return new SVG.ViewBox(this)
// otherwise act as a setter
return this.attr('viewBox', new SVG.ViewBox(x, y, width, height))
}
}
})
|